SendMessage是啥?
函數原型:
LRESULT SendMessage(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM IParam)
SendMessage(窗口句柄,消息,參數1,參數2)
函數功能:
該函數將指定的消息發送到一個或多個窗口。此函數為指定的窗口調用窗口程序,直到窗口程序處理完消息再返回。
在C#中,我們可以這樣用:
[DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
各個參數作用:
hWnd 發送消息總得有個目標,這個參數就是這樣用的。尋找要發送的窗口句柄有很多中方式,以下就是其中一種
[DllImport("user32.dll")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
Msg 指定發送的消息,這里以WM_SYSCOMMAND為例,大家可以在找到相關用法:https://docs.microsoft.com/zh-cn/windows/desktop/menurc/wm-syscommand
接下來的兩個參數都可以看以上的連接看到了。
因此,以下的代碼含義為向hwnd發送一個最小化的消息。
SendMessage(hwnd, WM_SYSCOMMAND, SC_MINIMIZE, 0)
怎么接收消息?
HwndSource hWndSource; WindowInteropHelper wih = new WindowInteropHelper(this); hWndSource = HwndSource.FromHwnd(wih.Handle); //添加處理程序 hWndSource.AddHook(MainWindowProc);
private static IntPtr MainWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { return IntPtr.Zero; }
以上的兩個代碼結合,就能處理發送過來的消息了。