- 1 year ago
Windows Form across processes - .net
To communicate between different processes running separate Windows Forms applications in .NET, you can use various inter-process communication (IPC) mechanisms. One common approach is to use named pipes, which allow bidirectional communication between processes. Here's a step-by-step guide to achieve this:
Step 1: Create a Named Pipe Server
- In your first Windows Forms application (the "server" application), create a named pipe server to listen for incoming connections.
csharpusing System;
using System.IO.Pipes;
using System.Windows.Forms;
public class NamedPipeServer
{
private NamedPipeServerStream serverPipe;
public void StartServer()
{
serverPipe = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, 1);
serverPipe.WaitForConnection();
// Do something with the data received
StreamReader reader = new StreamReader(serverPipe);
string data = reader.ReadLine();
MessageBox.Show($"Received data: {data}");
// Close the pipe after processing the data
serverPipe.Close();
}
}
Step 2: Create a Named Pipe Client
- In your second Windows Forms application (the "client" application), create a named pipe client to connect to the named pipe server and send data.
csharpusing System.IO.Pipes;
using System.Windows.Forms;
public class NamedPipeClient
{
public void SendData(string data)
{
using (NamedPipeClientStream clientPipe = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut))
{
clientPipe.Connect();
StreamWriter writer = new StreamWriter(clientPipe);
writer.WriteLine(data);
writer.Flush();
clientPipe.WaitForPipeDrain();
}
}
}
Step 3: Run Both Applications and Communicate
- In the server application, create an instance of the
NamedPipeServer
class and call theStartServer
method.
csharppublic partial class FormServer : Form
{
private NamedPipeServer pipeServer = new NamedPipeServer();
private void FormServer_Load(object sender, EventArgs e)
{
pipeServer.StartServer();
}
}
- In the client application, create an instance of the
NamedPipeClient
class and call theSendData
method whenever you want to send data to the server.
csharppublic partial class FormClient : Form
{
private NamedPipeClient pipeClient = new NamedPipeClient();
private void buttonSend_Click(object sender, EventArgs e)
{
string data = textBoxData.Text;
pipeClient.SendData(data);
}
}
Now, when you run both applications, you can enter data in the client application and click the "Send" button to send it to the server application. The server application will display a message box showing the received data.
Note: Make sure to handle exceptions, cleanup, and error scenarios in a real-world application. Additionally, you may consider using asynchronous methods for better performance and responsiveness.