//发送方 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace ExeToWinform { public partial class Form2 : Form { public Form2() { InitializeComponent(); } const int WM_COPYDATA = 0x004A; public struct COPYDATASTRUCT { public IntPtr dwData; public int cData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } [DllImport("User32.dll")] public static extern int SendMessage(int hwnd, int msg, int wParam, ref COPYDATASTRUCT IParam); [DllImport("User32.dll")] public static extern int FindWindow(string lpClassName, string lpWindowName); private void button1_Click(object sender, EventArgs e) { int WINDOW_HANDLE = FindWindow(null, "接受窗口"); if (WINDOW_HANDLE!=0) { byte[] arr = System.Text.Encoding.Default.GetBytes(textBox1.Text); int len = arr.Length; COPYDATASTRUCT cdata; cdata.dwData = (IntPtr)100; cdata.lpData = textBox1.Text; cdata.cData = len + 1; SendMessage(WINDOW_HANDLE, WM_COPYDATA, 0, ref cdata); } } } }
//接收方
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace TestPtr { public partial class Form1 : Form { public Form1() { InitializeComponent(); } const int WM_COPYDATA = 0x004A;//WM_COPYDATA消息的主要目的是允许在进程间传递只读数据。 //Windows在通过WM_COPYDATA消息传递期间,不提供继承同步方式。 //其中,WM_COPYDATA对应的十六进制数为0x004A public struct COPYDATASTRUCT { public IntPtr dwData; public int cData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } /// <summary> /// 接收消息 /// </summary> /// <param name="m"></param> protected override void DefWndProc(ref Message m) { switch (m.Msg) { case WM_COPYDATA: COPYDATASTRUCT cdata = new COPYDATASTRUCT(); Type mytype = cdata.GetType(); cdata = (COPYDATASTRUCT)m.GetLParam(mytype); this.label1.Text = cdata.lpData; break; default: base.DefWndProc(ref m); break; } } } }
欢迎加群交流 QQ群 830426796