WPF 利用HwndSource拦截Windows消息

来源:互联网 发布:js 判断对象是否存在 编辑:程序博客网 时间:2024/06/05 08:29

WPF提供了一个HwndSource可以使你更快的实现处理Windows消息。

通过HwndSource.FromHwnd得到的HwndSource可以添加(AddHook)移除(Remove)Hook

首先注册SourceInitialized事件,在事件中创建一个HwndSource对象,

然后利用其AddHook方法来将所有的windows消息附加到一个现有的事件中,这个就是WpfHandleWinowMsg。


代码如下:

 public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            SourceInitialized += HandleInitialized;        }        public void HandleInitialized(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)            {                case 1:                    break;                case 2:                    break;                default:                    break;            }            return IntPtr.Zero;        }    }



顺带说下Winform,直接重载WndProc函数即可

public partial class Form1 : Form{       int WM_NCLBUTTONDBLCLK = 0xA3;        protected override void WndProc(ref Message m)        {            if (m.Msg == WM_NCLBUTTONDBLCLK)            {                if (this.Height < 35)                {                    this.Height = h;                }                else                {                    h = this.Height;                    this.Height = -10;                }                return;            }            base.WndProc(ref m);  //让基类去处理        }}