C#实现窗口消息方法

1.定义消息

public const string MSG_TEST = "Msg_Test";

2.注册消息

	[DllImport("user32.dll", CharSet = CharSet.Unicode)]
    static extern uint RegisterWindowMessage(string lpProcName);
	uint Msg_Test = RegisterWindowMessage(MSG_TEST);

3.发送消息

SendMessage(0xFFFF,Msg_Test ,0,0);//0xFFFF为广播形式发送消息

4.接收消息

protected override void WndProc(ref System.Windows.Forms.Message e)
{
     if (e.Msg == Msg_Test)
     {
         MessageBox.Show("OK");
     }
     base.WndProc(ref e);
 }
 

总体代码:

 		public struct CopyDataStruct
        {
            public IntPtr dwData;
            public int cbData;

            [MarshalAs(UnmanagedType.LPStr)]

            public string lpData;
        }
        public const string MSG_TEST = "Msg_Test";
        //#define MSG_TEST "Msg_Test"

        //通过窗口的标题来查找窗口的句柄 
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        static extern uint RegisterWindowMessage(string lpProcName);

        uint Msg_Test = RegisterWindowMessage(MSG_TEST);
        //在DLL库中的发送消息函数
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage
            (
            int hWnd,                         // 目标窗口的句柄  
            uint Msg,                          // 在这里是WM_COPYDATA
            int wParam,                       // 第一个消息参数
            ref CopyDataStruct lParam        // 第二个消息参数
           );

        private void Send_Click(object sender, EventArgs e)
        {
            CopyDataStruct cds;
            cds.dwData = (IntPtr)1; //这里可以传入一些自定义的数据,但只能是4字节整数      
            cds.lpData = "d";    //消息字符串
            cds.cbData = System.Text.Encoding.Default.GetBytes("d").Length + 1;
            int hwd = FindWindow(null, null); //"Client");
            SendMessage(0xFFFF, Msg_Test, 0, ref cds);
        }

你可能感兴趣的:(C++)