C#中发送消息给指定的窗口,以及接收消息.docxVIP

  • 27
  • 0
  • 约2.44千字
  • 约 3页
  • 2021-10-12 发布于陕西
  • 举报

C#中发送消息给指定的窗口,以及接收消息.docx

C#中发送消息给指定的窗口,以及接收消息 如何在C#中发送消息给指定的窗口? public class Note { //声明 API 函数 [DllImport(\ private static extern IntPtr SendMessage(int hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport(\ private static extern int FindWindow(string lpClassName, string lpWindowName); //定义消息常数 public const int CUSTOM_MESSAGE = 0X400 + 2;//自定义消息 //向窗体发送消息的函数 public void SendMsgToMainForm(int MSG) { int WINDOW_HANDLER = FindWindow(null, \协同标绘\ if (WINDOW_HANDLER == 0) { throw new Exception(\ } long result = SendMessage(WINDOW_HANDLER, CUSTOM_MESSAGE, new IntPtr(14), IntPtr.Zero).ToInt64(); } } 在协同标绘窗口里拦截消息的函数: protected override void WndProc(ref System.Windows.Forms.Message msg) { switch (msg.Msg) { case Note.CUSTOM_MESSAGE: //处理消息 { switch (msg.WParam.ToString()) { case \对象添加 string s = \ addOne(s); break; case \对象更新 string sn = \ updateID(sn); break; case \对象删除 deleteID(\ break; case \与会者信息更新 updateClientInfor(\张三_在线\ break; } } break; default: base.WndProc(ref msg);//调用基类函数处理非自定义消息。 break; } } private void button1_Click(object sender, EventArgs e) { Note a = new Note(); a.SendMsgToMainForm(Note.CUSTOM_MESSAGE); } FindWindow()函数的用法。要在C#里使用该API,写出FindWindow()函数的声明: [DllImport(\ private extern static IntPtr FindWindow(string lpClassName, string lpWindowName); 这个函数有两个参数,第一个是要找的窗口的类,第二个是要找的窗口的标题,是窗体的Text名字,不是name。在搜索的时候不一定两者都知道,但至少要知道其中的一个。有的窗口的标题是比较容易得到的,如\计算器\,所以搜索时应使用标题进行搜索。但有的软件的标题不是固定的,如\记事本\,如果打开的文件不同,窗口标题也不同,这时使用窗口类搜索就比较方便。如果找到了满足条件的窗口,这个函数返回该窗口的句柄,否则返回0。 看例子 IntPtr ParenthWnd = new IntPtr(0);

文档评论(0)

1亿VIP精品文档

相关文档