本文介绍在C#中如何使用和自定义Windows消息实现进程间的通信,并传递一个字符串类型。
工具/原料
Visual Studio 2013(其他版本亦可)。
基础知识
1、在C#中,我们可以使用PostMessage或SendMessage向目标窗口发送消息,并重载目标窗口的消息处理函数WndProc来响应消息。自定义消息的边界是0x0400,我们自定义的消息应当比它大。
2、为了传递字符串,我们需要把托管的string类型封送到非托管内存中,而在目标窗口从非托管内存中提取字符串,使用Marshal.StringToHGlobalAuto()和Marshal.PtrToStringAuto()即可。
举例
1、新建C# WinForm项目,并命名为“CS自定义消息”,如下图:
2、修改主窗体,布局如下:
3、添加新建窗体,并布局如下:
4、添加公开类Win32Api,代码如下:public class Win32Api { #re爿讥旌护gion msg public const int USER = 0x0400; public const int UM_1 = USER + 1; #endregion #region api [DllImport("user32.dll")] public static extern void PostMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam); #endregion }
5、在Form1中添加代码,如下: public partial class Form1 : Form { IntPtr h; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { var f = new Form2(); h = f.Handle; f.Show(); } private void button2_Click(object sender, EventArgs e) { string str=textBox1 .Text ; IntPtr i=Marshal .StringToHGlobalAuto (str); Win32Api .PostMessage (h,Win32Api.UM_1 ,0,i); } }
6、在Form2中添加代码,如下: public partial class Form2 : Form { publi艘早祓胂c Form2() { InitializeComponent(); } protected override void WndProc(ref Message m) { switch (m.Msg) { case Win32Api .UM_1 : string str = Marshal.PtrToStringAuto(m.LParam); textBox1.Text += str+Environment .NewLine ; break; default : base.WndProc(ref m); break; } } }
7、调试运行,结果如下: