当前位置:   article > 正文

C# message简单实现窗口间信息接收与发送_c# wm_user 消息为空

c# wm_user 消息为空

刚接触windows 不同程序 窗口消息传递,不理解IntPtr SendMessage(int hWnd, int msg, IntPtr wParam, IntPtr lParam)这函数怎么用?消息内容怎么传递过去,还遇到需要message结构体?IntPtr怎么用呢?

但实际只是用来传个数据,不需要这么复杂,就简单写了下面程序。


1.发送端


  1. public partial class Form1 : Form
  2. {
  3. private const int WM_USER = 0x0400; //自定义消息号一般开始于0x0400,
  4. [DllImport("User32.dll", EntryPoint = "SendMessage")]
  5. private static extern IntPtr SendMessage(int hWnd, int msg, IntPtr wParam, IntPtr lParam); //发送消息函数。
  6. //找出窗口句柄handler,用起来方便。有看到过返回值时IntPtr
  7. [DllImport("User32.dll", EntryPoint = "FindWindow")]
  8. private static extern int FindWindow(string lpClassName, string lpWindowName);
  9. public Form1()
  10. {
  11. InitializeComponent();
  12. this.Text = "消费者";
  13. label1.Text = "向X300A";
  14. }
  15. private void button1_Click(object sender, EventArgs e)
  16. {
  17. int WINDOW_HANDLER; //
  18. int msgNum;
  19. if(int.TryParse(textBox1.Text,out msgNum)==false) //获取用户信息内容,这里只接受数字。
  20. {
  21. return;
  22. }
  23. WINDOW_HANDLER = FindWindow(null, "X300A");//通过窗口标题,获得句柄
  24. SendMessage(WINDOW_HANDLER, WM_USER, new IntPtr(msgNum), IntPtr.Zero);//前面两个参数,基本固定格式。
  25. //后面两个参数,把需要传递的参数转为IntPtr,就好了。
  26. //第四个参数因为没什么传的,这里就设为空
  27. }
  28. }


2.接收端


  1. public partial class Form1 : Form
  2. {
  3. private const int WM_USER = 0x0400; //自定义消息号一般开始于0x0400,发送端也是设置成这个
  4. public Form1()
  5. {
  6. InitializeComponent();
  7. this.Text = "X300A";
  8. label1.Text = "接收消费者信息";
  9. }
  10. protected override void WndProc(ref Message m) //重新函数,处理接收的信息
  11. {
  12. switch (m.Msg)
  13. {
  14. case WM_USER:
  15. string message = m.WParam.ToString(); //转换成string类型,这样就能接收到发送端信息。
  16. textBox1.AppendText("接受到信息:"+message+"\n");
  17. Popup p1 = new Popup(); //自定义的一个窗口
  18. if(p1.ShowDialog()==DialogResult.OK)
  19. {
  20. p1.Dispose();
  21. textBox1.AppendText("启动完毕\n");
  22. }
  23. break;
  24. default: break;
  25. }
  26. base.WndProc(ref m);
  27. }
  28. }

3.演示图



参考链接:

http://blog.sina.com.cn/s/blog_45eaa01a01013zbs.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/45181
推荐阅读
相关标签
  

闽ICP备14008679号