winform进程之间传递消息
两个进程FF.exe与JJ.EXE分别是发送方和接受方
发送方:
#region 向进程发送消息
const int WM_COPYDATA = 0x004A;
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
ref COPYDATASTRUCT lParam // second message parameter
);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
#endregion
//在需要调用的地方添加代码:
private void button1_Click(object sender, EventArgs e)
{
//int WINDOW_HANDLER = FindWindow(null, @"接受方窗体的text属性");
int WINDOW_HANDLER = FindWindow(null, @"Frmbbb");
if (WINDOW_HANDLER != 0)
{
byte[] sarr = System.Text.Encoding.Default.GetBytes(this.textBox1.Text);
int len = sarr.Length;
COPYDATASTRUCT cds;
cds.dwData = (IntPtr)100;
cds.lpData = "这里是传送的消息";
cds.cbData = len + 1;
SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds);
}
}
接受方:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#region 接受方接受传来的消息
const int WM_COPYDATA = 0x004A;
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
COPYDATASTRUCT mystr = new COPYDATASTRUCT();
Type mytype = mystr.GetType();
mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
this.textBox1.Text = mystr.lpData;//要接受消息的地方
break;
default:
base.DefWndProc(ref m);
break;
}
}
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
#endregion
这样就可以完成两个进程传递消息。