ITPub博客

首页 > Linux操作系统 > Linux操作系统 > winform进进程之间传递消息

winform进进程之间传递消息

原创 Linux操作系统 作者:fangqm 时间:2011-06-29 11:41:15 0 删除 编辑
发送方:
#region 向进程发送消息
        const int WM_COPYDATA = 0x004A;
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(
            int hWnd, // handle to destination window
            int Msg, // message
            int wParam, // first message parameter
            ref COPYDATASTRUCT lParam // second message parameter
        );
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
        #endregion
使用时在相应事件中添加代码
              int WINDOW_HANDLER = FindWindow(null, @"接受方窗体的text属性");
            if (WINDOW_HANDLER != 0)
            {
                byte[] sarr = System.Text.Encoding.Default.GetBytes(this.textBox1.Text);
                int len = sarr.Length;
                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)100;
                cds.lpData = this.textBox1.Text;//cds.IpData是要传递的值
                cds.cbData = len + 1;
                SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds);
            }
 
接受方:
#region 接受方接受传来的消息
        const int WM_COPYDATA = 0x004A;
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
                case WM_COPYDATA:
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    this.textBox1.Text = mystr.lpData;//接受传过来的值
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
        #endregion

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/23109131/viewspace-700953/,如需转载,请注明出处,否则将追究法律责任。

下一篇: pictureBox
请登录后发表评论 登录
全部评论

注册时间:2010-03-24

  • 博文量
    298
  • 访问量
    729640