C#中使用自定义消息

 

消息发送方

一、引入命名空间

using System.Runtime.InteropServices;

二、消息定义

        //自定义的消息

        public const int USER = 0x500;

        public const int MYMESSAGE = USER + 1;

三、自定义结构体

 public  struct My_lParam

        {

            public int i;

            public string s;

        }

四、重写函数

        //消息发送API

        [DllImport("User32.dll", EntryPoint = "SendMessage")]

        private static extern int SendMessage(

        IntPtr hWnd,        // 信息发往的窗口的句柄

        int Msg,            // 消息ID

        int wParam,         // 参数1

        ref My_lParam lParam

        );

五、获取窗体句柄的函数引入

        [DllImport("User32.dll", EntryPoint = "FindWindow")]

        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

六、消息发送

            IntPtr ptr = FindWindow(null, "Form1");//获取接收消息的窗体句柄

            //消息构建

            My_lParam m = new My_lParam();

            m.s = textBox1.Text;

            m.i = m.s.Length;

            SendMessage(ptr, MYMESSAGE, 1, ref m);//发送消息



 

消息接收方(Form1)

一、引入命名空间

using System.Runtime.InteropServices;

二、消息定义

        //自定义的消息

        public const int USER = 0x500;

        public const int MYMESSAGE = USER + 1;

三、重写窗体的消息处理函数

       ///重写窗体的消息处理函数DefWndProc,从中加入自己定义消息 MYMESSAGE 的检测的处理入口

        protected override void DefWndProc(ref Message m)

        {

            switch (m.Msg)

            {

                //接收自定义消息MYMESSAGE,并显示其参数

                case MYMESSAGE:

                    Form2.My_lParam ml = new Form2.My_lParam();

                    Type t = ml.GetType();

                    ml = (Form2.My_lParam)m.GetLParam(t);

                    label1.Text = ml.s;

                    break;

                default:

                    base.DefWndProc(ref m);

                    break;

            }

        }

 

LParam中可能包含的是一个指向字符串的指针,如char *,那么这时候如何取得LParam中的实际数据呢?

以一自定义消息为例,通过该消息的m.LParam.ToString()得知存储的数据类型为"String",

但是使用GetLParam获取会出现错误,因为GetLParam只接受结构类型,那怎么办呢?

那就是使用Marshal.Copy,将数据从非托管内存指针复制到托管 8 位无符号整数数组.

如下:

byte[] ch = new byte[256]

System.Runtime.InteropServices.Marshal.Copy(m.LParam,ch,0,255);

string str = System.Text.Encoding.Default.GetString(ch);

这样,就成功获得了m.LParam所包含的字符数据。

转载于:https://my.oschina.net/ucliaohh/blog/500497

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值