C#进程间通信
消息发送方
一、引入系统方法SendMessage
private const int WM_COPYDATA = 0x004A;//这个不要随意更改,否则可能造成读取数据报错 [DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref COPYDATASTRUCT lParam);
二、声明数据传输结构体
public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; }
三、消息发送
Process? process = Process.GetProcessesByName("WinFormsApp2").FirstOrDefault(); if (process == null) { MessageBox.Show("指定进程未找到"); return; } string message = "0012001256"; COPYDATASTRUCT cds; cds.dwData = (IntPtr)Convert.ToInt16(1);//可以是任意值 cds.cbData = bytes.Length + 1;//指定lpData内存区域的字节数 cds.lpData = message;//发送给目标窗口所在进程的数据 SendMessage(process.MainWindowHandle, WM_COPYDATA, 0, ref cds);
消息接收方,进程名称“WinFormsApp2”
public partial class Form1 : Form { private const int WM_COPYDATA = 0x004A;//这个不要随意更改,否则可能造成读取数据报错 public Form1() { InitializeComponent(); } protected override void DefWndProc(ref Message m) { switch (m.Msg) { case WM_COPYDATA: COPYDATASTRUCT cds = new COPYDATASTRUCT(); cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT)); string result = cds.lpData; MessageBox.Show($"收到消息:{result}"); break; default: base.DefWndProc(ref m); break; } } } public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; }
最近评论