要传递结构体
public struct STUDENT { public int id; //ID public string name; //姓名 }
要引用Win32api函数FindWindow,SendMessage
/// <summary> /// 查找窗体句柄 /// </summary> /// <param name="lpClassName">指定的类名</param> /// <param name="lpWindowName">指定的窗口名称</param> /// <returns>返回窗口句柄</returns> [DllImport("User32.dll", EntryPoint = "FindWindow")] public static extern IntPtr FindWindow( string lpClassName, string lpWindowName); /// <summary> /// 查找窗体句柄 /// </summary> /// <param name="hwndParent">父窗口句柄</param> /// <param name="hwndChildAfter">子窗口句柄</param> /// <param name="lpClassName">窗口类名</param> /// <param name="lpWindowName">窗口名称</param> /// <returns></returns> [DllImport("User32.dll", EntryPoint = "FindWindowEx")] public static extern IntPtr FindWindowEx( IntPtr hwndParent, IntPtr hwndChildAfter, string lpClassName, string lpWindowName); [DllImport("User32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage( IntPtr hWnd, // 窗口句柄 int Msg, // message int wParam, // first message parameter IntPtr lParam); // second message parameter
3,还要定义个消息
public const int WM_COPYDATA = 0X004A;
也可以发送自定义消息 public const int WM_USER = 1024; //自定义消息
4,发送消息
//先查找要发送的窗口句柄 IntPtr nRet = Win32API.FindWindowEx(IntPtr.Zero, IntPtr.Zero,null , "Form2"); if (nRet == IntPtr.Zero) MessageBox.Show("没有找到指定的窗口"); STUDENT stu = new STUDENT(); stu.id = 101; stu.name = "我是发送者"; IntPtr stuPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(STUDENT))); Marshal.StructureToPtr(stu, stuPtr, false); SendMessage(nRet, WM_COPYDATA, 0, stuPtr);
//用PostMessage发送消息
//PostMessage(nRet, WM_USER, 0, stuPtr);
5,在接收窗口中重写DefWndProc函数
public const int WM_COPYDATA = 0X004A; public const int WM_USER = 1024; //自定义消息
protected override void DefWndProc(ref Message m) { if(m.Msg==WM_COPYDATA) { STUDENT stu = (STUDENT)Marshal.PtrToStructure(m.LParam, typeof(STUDENT)); textBox1.Text = stu.name;
return; }
if(m.Msg==WM_USER)
{
STUDENT stu = (STUDENT)Marshal.PtrToStructure(m.LParam, typeof(STUDENT));
textBox1.Text = stu.name;
return;
}
base.DefWndProc(ref m); }
6,在接收窗口也要定义WM_COPYDATA消息,和结构体,
7,在WM_COPYDATA传递COPYDATASTRUCT结构体也是可行的
IntPtr cdsPtr = IntPtr.Zero;
cdsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(COPYDATASTRUCT)));
Marshal.StructureToPtr(cds, cdsPtr, false);
SendMessage(nRet, WM_COPYDATA, 0, cdsPtr);
接收窗口中
COPYDATASTRUCT cds = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT));
textBox1.Text = cds.lpData;
注意:要用Marshal类要加命名空间 using System.Runtime.InteropServices;
今天就弄到这了,其他的API以后有时间再弄