Wpf发送接收 win32消息

#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);

        /// 
        /// 返回wpf主窗体句柄
        /// 
        /// wpf进程名
        /// 
        public static IntPtr  GetWpfMainwindowHandel(string processName)
        {            
            return Process.GetProcesses().FirstOrDefault(t => t.ProcessName.Contains(processName))?.MainWindowHandle??IntPtr.Zero;
        }
        /// 
        /// 发送win32消息给wpf窗口
        /// 
        /// 窗口句柄
        /// 字符串消息
        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");
            }
        }

        /// 
        /// wpf窗口订阅win32消息
        /// 
        /// wpf窗口
        /// 接收到win32消息时要处理的action
        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)=>
            {
          if ( msg ==
WM_COPYDATA )
          {
             Win32Message m = (Win32Message)Marshal.PtrToStructure(iparam, typeof(Win32Message));
            action
?.Invoke(m.lpData);
          }
         
return IntPtr.Zero;
       });
     }

#endregion

 

转载于:https://www.cnblogs.com/nocanstillbb/p/10488511.html

你可能感兴趣的:(Wpf发送接收 win32消息)