none
PostMessage 不能正确发送自定义的复杂结构体struct RRS feed

  • 问题

  • 各位大侠好!
      我在C#里使用Win32 API来收发系统消息。如果使用User32.dll中的PostMessage()来发送整数的wParam和结构体(有一个string成员)的lParam,接受者无法收到正确的lParam,但可以收到wParam。如果使用SendMessage(),2个参数都能正确接受。
     
      但是我的程序需要以异步方式使用PostMessage,请帮我看看代码里有什么错误。非常感谢。
     
      说明:代码来源 http://www.cnblogs.com/kevinGao/archive/2011/10/30/2231524.html

    //Win32 API 类


    using System;
    using System.Runtime.InteropServices;

    namespace TestHwnd
    {
        public class Win32API
        {
           


            [DllImport("User32.dll", EntryPoint = "FindWindow")]
            public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

            [DllImport("User32.dll", EntryPoint = "FindWindowEx")]
            public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpClassName, string lpWindowName);

            /// <summary>
            /// 自定义的结构
            /// </summary>
            public struct My_lParam
            {
                public int i;
                public string s;
            }
            /// <summary>
            /// 使用COPYDATASTRUCT来传递字符串
            /// </summary>
            [StructLayout(LayoutKind.Sequential)]
            public struct COPYDATASTRUCT
            {
                public IntPtr dwData;
                public int cbData;
                [MarshalAs(UnmanagedType.LPStr)]
                public string lpData;
            }
            //消息发送API
            [DllImport("User32.dll", EntryPoint = "SendMessage")]
            public static extern int SendMessage(
                IntPtr hWnd,        // 信息发往的窗口的句柄
                int Msg,            // 消息ID
                int wParam,         // 参数1
                int lParam          //参数2
            );

           
            //消息发送API
            [DllImport("User32.dll", EntryPoint = "SendMessage")]
            public static extern int SendMessage(
                IntPtr hWnd,        // 信息发往的窗口的句柄
                int Msg,            // 消息ID
                int wParam,         // 参数1
                ref My_lParam lParam //参数2
            );
           
            //消息发送API
            [DllImport("User32.dll", EntryPoint = "SendMessage")]
            public static extern int SendMessage(
                IntPtr hWnd,        // 信息发往的窗口的句柄
                int Msg,            // 消息ID
                int wParam,         // 参数1
                ref  COPYDATASTRUCT lParam  //参数2
            );

            //消息发送API
            [DllImport("User32.dll", EntryPoint = "PostMessage")]
            public static extern int PostMessage(
                IntPtr hWnd,        // 信息发往的窗口的句柄
                int Msg,            // 消息ID
                int wParam,         // 参数1
                int lParam            // 参数2
            );
           
           
           
            //消息发送API
            [DllImport("User32.dll", EntryPoint = "PostMessage")]
            public static extern int PostMessage(
                IntPtr hWnd,        // 信息发往的窗口的句柄
                int Msg,            // 消息ID
                int wParam,         // 参数1
                ref My_lParam lParam //参数2
            );
           
            //异步消息发送API
            [DllImport("User32.dll", EntryPoint = "PostMessage")]
            public static extern int PostMessage(
                IntPtr hWnd,        // 信息发往的窗口的句柄
                int Msg,            // 消息ID
                int wParam,         // 参数1
                ref  COPYDATASTRUCT lParam  // 参数2
            );

        }
    }

    //主窗体,发送消息


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;

    namespace TestHwnd
    {
        public partial class Main : Form
        {

            public IntPtr hwndTest;
            public int IwndTest;
            public IntPtr hwndfrmTest;
           

            public Main()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                Test test = new Test();
                test.Show(this);
            }

            private void timer1_Tick(object sender, EventArgs e)
            {
                string strTest = "25425";
                Win32API.COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)100;
                cds.lpData = strTest;
                byte[] sarr = System.Text.Encoding.UTF8.GetBytes(strTest);
                int len = sarr.Length;
                cds.cbData = len + 1;
               
                Win32API.My_lParam lp=new Win32API.My_lParam();
                lp.i=3;
                lp.s="test";
               
                if(hwndTest!=(IntPtr)0)
                {
                    if (DateTime.Now.Second % 2 == 0)
                    {
                        Win32API.SendMessage(hwndTest, 0x60, 1, 3);//传递2个整型参数成功
                    }
                    if(DateTime.Now.Second % 3 == 0)
                    {
                        Win32API.SendMessage(hwndTest, 0x61, 5, ref lp);//传递整型参数和结构类型成功,这个方法加以改变后可以传递对象
                    }
                    if(DateTime.Now.Second % 5 == 0)
                    {
                        Win32API.SendMessage(hwndTest, 0x62, 5, ref cds);//传递整型参数和不定长的字符串成功
                    }
                    if(DateTime.Now.Second % 7 == 0)
                    {
                        Win32API.PostMessage(hwndTest, 0x63, 5, 6);//传递2个整型参数成功
                    }
                    if(DateTime.Now.Second % 9 == 0)
                    {
                        Win32API.PostMessage(hwndTest, 0x64, 3, ref lp);//传递整型参数成功,但是传递参数lp失败,3可以传递成功。
                    }
                    if(DateTime.Now.Second % 11 == 0)
                    {
                        Win32API.PostMessage(hwndTest, 0x65, 3, ref cds);//传递整型参数成功,传递参数cds失败,3可以传递成功。
                    }
                }
               
               
            }
        }
    }

     


    //子窗体接收消息以及参数

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;

    namespace TestHwnd
    {
        public partial class Test : Form
        {
            Main main;
            public Test()
            {
                InitializeComponent();
            }

            private void Test_Load(object sender, EventArgs e)
            {
                main = this.Owner as Main;
                main.hwndTest = this.Handle;
               
            }

           

            ///重写窗体的消息处理函数DefWndProc,从中加入自己定义消息的检测的处理入口
            protected override void DefWndProc(ref Message m)
            {
                switch (m.Msg)
                {
                        //接收自定义消息MYMESSAGE,并显示其参数
                    case 0x60:
                        {
                            label1.Text = DateTime.Now.ToString() + "-" + m.WParam.ToInt32().ToString() + "-" + m.LParam.ToInt32().ToString();
                        }
                        break;
                    case 0x61:
                        {
                            Win32API.My_lParam ml = new Win32API.My_lParam();
                            Type t = ml.GetType();
                            ml = (Win32API.My_lParam)m.GetLParam(t);
                            label2.Text = DateTime.Now.ToString() + "-" + m.WParam.ToInt32().ToString() + "-" + ml.i.ToString()+":"+ml.s;
                        }
                        break;
                        case 0x62:
                        {
                            Win32API.COPYDATASTRUCT mystr = new Win32API.COPYDATASTRUCT();
                            Type mytype = mystr.GetType();
                            mystr = (Win32API.COPYDATASTRUCT)m.GetLParam(mytype);
                            string str2 = mystr.lpData;
                            label3.Text = DateTime.Now.ToString() + "-" + m.WParam.ToInt32().ToString() + "-" + str2;
                        }
                        break;
                        case 0x63:
                        {
                            label4.Text = DateTime.Now.ToString() + "-" + m.WParam.ToInt32().ToString() + "-" + m.LParam.ToInt32().ToString();
                        }
                        break;
                        case 0x64:
                        {
                            Win32API.My_lParam ml = new Win32API.My_lParam();
                            Type t = ml.GetType();
                            ml = (Win32API.My_lParam)m.GetLParam(t);
                            label5.Text = DateTime.Now.ToString() + "-" + m.WParam.ToInt32().ToString() + "-" + ml.i.ToString()+":"+ml.s;
                        }
                        break;
                        case 0x65:
                        {
                            Win32API.COPYDATASTRUCT mystr = new Win32API.COPYDATASTRUCT();
                            Type mytype = mystr.GetType();
                            mystr = (Win32API.COPYDATASTRUCT)m.GetLParam(mytype);
                            string str2 = mystr.lpData;
                            label6.Text = DateTime.Now.ToString() + "-" + m.WParam.ToInt32().ToString() + "-" + str2;
                        }
                        break;
                    default:
                        base.DefWndProc(ref m);
                        break;
                }
            }

           
            private void button1_Click(object sender, EventArgs e)
            {
                main.hwndTest = (IntPtr) (0);
                this.Close();
            }

           

     

        }

       
    }

    • 已移动 Leo Liu - MSFT 2012年1月10日 7:44 Moved for better support. (发件人:Visual C#)
    2012年1月9日 13:28

答案

  • 感謝版主,試了一下,OK哦~


    Win32API.cs加入

    [DllImport("User32.dll", EntryPoint = "PostMessage")]
    public static extern int PostMessage(
        IntPtr hWnd,        // 信息发往的窗口的句柄
        int Msg,            // 消息ID
        int wParam,         // 参数1
        IntPtr lParam  // 参数2
    );

    //Initialize unmanged memory to hold the struct.
    IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(lp));
    // Copy the struct to unmanaged memory.
    Marshal.StructureToPtr(lp, pnt, false);
    Win32API.PostMessage(hwndTest, 0x64, 3, pnt);

    or

    //Initialize unmanged memory to hold the struct.
    IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(cds));
    // Copy the struct to unmanaged memory.
    Marshal.StructureToPtr(cds, pnt, false);
    Win32API.PostMessage(hwndTest, 0x65, 3, pnt);//传递整型参数成功,传递参数cds失败,3可以传递成功。

    Marshal.StructureToPtr 方法(http://msdn.microsoft.com/zh-tw/library/system.runtime.interopservices.marshal.structuretoptr.aspx)


    亂馬客blog: http://www.dotblogs.com.tw/rainmaker/
    2012年1月10日 7:01

全部回复

  • Marshal.StructureToPtr 方法 传递指针

     

    接收再转回来


    http://feiyun0112.cnblogs.com/
    • 已建议为答案 亂馬客 2012年1月10日 7:02
    2012年1月10日 6:24
    版主
  • 感謝版主,試了一下,OK哦~


    Win32API.cs加入

    [DllImport("User32.dll", EntryPoint = "PostMessage")]
    public static extern int PostMessage(
        IntPtr hWnd,        // 信息发往的窗口的句柄
        int Msg,            // 消息ID
        int wParam,         // 参数1
        IntPtr lParam  // 参数2
    );

    //Initialize unmanged memory to hold the struct.
    IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(lp));
    // Copy the struct to unmanaged memory.
    Marshal.StructureToPtr(lp, pnt, false);
    Win32API.PostMessage(hwndTest, 0x64, 3, pnt);

    or

    //Initialize unmanged memory to hold the struct.
    IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(cds));
    // Copy the struct to unmanaged memory.
    Marshal.StructureToPtr(cds, pnt, false);
    Win32API.PostMessage(hwndTest, 0x65, 3, pnt);//传递整型参数成功,传递参数cds失败,3可以传递成功。

    Marshal.StructureToPtr 方法(http://msdn.microsoft.com/zh-tw/library/system.runtime.interopservices.marshal.structuretoptr.aspx)


    亂馬客blog: http://www.dotblogs.com.tw/rainmaker/
    2012年1月10日 7:01