WPF 利用HwndSource拦截 Windows系统消息
首先要获取窗体句柄,获取方法:http://www.xqblog.top/post/152.html
通过HwndSource.FromHwnd得到的HwndSource可以添加(AddHook)移除(Remove)Hook
例如:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Loaded+= MainWindow_Load; Closed+= MainWindow_Closed; } public void MainWindow_Load(object o,EventArgs e) { IntPtr wptr = new WindowInteropHelper(this).Handle; HwndSource hs = HwndSource.FromHwnd(wptr); hs.AddHook(new HwndSourceHook(WpfHandleWinowMsg)); } public IntPtr WpfHandleWinowMsg(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { //这个函数可以做很多事情,只要是windows消息都会经过 //也可以调API做对应的事情 switch (msg) { default: break; } return IntPtr.Zero; } public void MainWindow_Closed(object o,EventArgs e) { IntPtr wptr = new WindowInteropHelper(this).Handle; HwndSource hs = HwndSource.FromHwnd(wptr); hs.Remove(new HwndSourceHook(WpfHandleWinowMsg)); } }