转自:https://i.cnblogs.com/EditArticles.aspx?opt=1
/// <summary> /// 定义结构体 /// </summary> public struct COPYDATASTRUCT { public IntPtr dwData; //可以是任意值 public int cbData; //指定lpData内存区域的字节数 [MarshalAs(UnmanagedType.LPStr)] public string lpData; //发送给目录窗口所在进程的数据 }
发送方:
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(int hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam); [DllImport("User32.dll", EntryPoint = "FindWindow")] private static extern int FindWindow(string lpClassName, string lpWindowName); const int WM_COPYDATA = 0x004A;//必须是这个数值,不能更改 private void btnSend_Click(object sender, EventArgs e) { int hWnd = FindWindow(null, @"消息接受者"); if (hWnd == 0) { MessageBox.Show("未找到消息接受者!"); } else { string sendString = "测试发送数据"; byte[] sarr = System.Text.Encoding.Default.GetBytes(sendString); int len = sarr.Length; COPYDATASTRUCT cds; cds.dwData = (IntPtr)0 ; cds.cbData = len + 1; cds.lpData = sendString; SendMessage(hWnd, WM_COPYDATA, 0, ref cds); }}
接受方:
private static int WMA_InterPro = 0x004A;
protected override void DefWndProc(ref Message m) { if (m.Msg == WMA_InterPro) { COPYDATASTRUCT cds = new COPYDATASTRUCT(); Type t = cds.GetType(); cds = (COPYDATASTRUCT)m.GetLParam(t); string receiveInfo=cds.lpData; } else { base.DefWndProc(ref m); } }