码迷,mamicode.com
首页 > Windows程序 > 详细

Wpf发送接收 win32消息

时间:2019-03-07 11:36:43      阅读:373      评论:0      收藏:0      [点我收藏+]

标签:contain   tor   processes   set   窗口   lse   rsh   name   style   

        #region WPF发送和接收win32消息
        public const int WM_GETTEXT = 0x0D;
        public const int WM_SETTEXT = 0x0C;
        public const int WM_SIZEING = 0x0214;
        public const int WM_COPYDATA = 0x004A;
        public const int WM_LBUTTONDBLCLK = 0x0203;

        public struct Win32Message
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs (UnmanagedType.LPStr)]
            public string lpData;
        }

        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, ref Win32Message lParam);

        /// <summary>
        /// 返回wpf主窗体句柄
        /// </summary>
        /// <param name="processName">wpf进程名</param>
        /// <returns></returns>
        public static IntPtr  GetWpfMainwindowHandel(string processName)
        {            
            return Process.GetProcesses().FirstOrDefault(t => t.ProcessName.Contains(processName))?.MainWindowHandle??IntPtr.Zero;
        }
        /// <summary>
        /// 发送win32消息给wpf窗口
        /// </summary>
        /// <param name="wpfWinHandel">窗口句柄</param>
        /// <param name="message">字符串消息</param>
        public static void SendWin32MessageToWpfWindow(IntPtr wpfWinHandel,string message )
        {
            if (wpfWinHandel != IntPtr.Zero)
            {
                var param = new Win32Message
                {
                    dwData = (IntPtr)100,
                    cbData = System.Text.Encoding.Default.GetBytes(message).Length,
                    lpData = message,
                };
                SendMessage(wpfWinHandel, WM_COPYDATA, 0, ref param);
            }
            else
            {
                Console.WriteLine("wpf窗口句柄为zero");
            }
        }

        /// <summary>
        /// wpf窗口订阅win32消息
        /// </summary>
        /// <param name="window">wpf窗口</param>
        /// <param name="action">接收到win32消息时要处理的action</param>
        public static void SubWin32Message(System.Windows.Window window,Action<string> action)
        {
            WindowInteropHelper win = new WindowInteropHelper(window);
            HwndSource hwndSource = HwndSource.FromHwnd(win.Handle);
            hwndSource.AddHook((IntPtr hwnd,int msg,IntPtr wparam,IntPtr iparam,ref bool handel)=>
            {
                Win32Message m = (Win32Message)Marshal.PtrToStructure(iparam, typeof(Win32Message));
                action?.Invoke(m.lpData);
                return IntPtr.Zero;
            });
        }


        #endregion

 

Wpf发送接收 win32消息

标签:contain   tor   processes   set   窗口   lse   rsh   name   style   

原文地址:https://www.cnblogs.com/nocanstillbb/p/10488511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!