zoukankan      html  css  js  c++  java
  • WPF 利用HwndSource拦截Windows消息

    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);  //让基类去处理
            }
    }


  • 相关阅读:
    前端图片预览
    理解 Promise 过程
    node 小例子 集合
    各大网站处理 高 retina屏 边框 方法
    用js 创建  简单查找 删除 二叉树
    Python_快速安装第三方库-pip
    Python-找字典中公共key-zip reduce lambda
    Python-对字典进行排序
    Python-统计序列中元素
    Python-为元组中每个元素命名
  • 原文地址:https://www.cnblogs.com/kevinWu7/p/10163524.html
Copyright © 2011-2022 走看看