WinForm中使用Win32API发送自定义消息

I let AppA's Button1 to invoke the Button1_click event in AppB
In AppB I wrote:
        private string msgstr = "interprocess communication";
        private uint msg;
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);
        private void Form1_Load(object sender, System.EventArgs e)
        {
            msg = RegisterWindowMessage(msgstr);
            if (msg == 0)
            {
                MessageBox.Show(Marshal.GetLastWin32Error().ToString());
            }
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            MessageBox.Show("AppB's button is clicked");
        }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == msg)
            {
                //MessageBox.Show(msgstr + " from wndproc");
                button1.PerformClick();
            }
            base.WndProc(ref m);
        }
And in AppA I wrote:
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool PostMessage(int hhwnd, uint msg, IntPtr wparam,
        IntPtr lparam);
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);

        private string msgstr = "interprocess communication";
        private uint msg;
        private const int HWND_BROADCAST = 0xffff;
        private void button1_Click(object sender, System.EventArgs e)
        {
            msg = RegisterWindowMessage(msgstr);
            if (msg == 0)
            {
                MessageBox.Show(Marshal.GetLastWin32Error().ToString());
            }
            PostMessage(HWND_BROADCAST, msg, IntPtr.Zero, IntPtr.Zero);
        }
PS. Both should using System.Runtime.InteropServices;if PostMessage doesn't work you can try SendMessage

你可能感兴趣的:(WinForm)