WPF 注册全局热键

本文介绍了在WPF中如何注册和处理全局热键。由于WPF本身不提供API,需要借助Windows API的RegisterHotKey和UnregisterHotKey函数。键代码参照微软官方文档,同时提供了注销热键的方法,并给出注册F4热键的示例。
摘要由CSDN通过智能技术生成

在wpf中是没有注册热键的API的
需要调用到以下两个函数

//返回值不为0即注册成功
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);//注册热键
  
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);//注销热键

RegisterHotKey函数参考
https://learn.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-registerhotkey
UnregisterHotKey函数参考
https://learn.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-unregisterhotkey

注册热键

        private IntPtr _windowHandle;
        private HwndSource _source;
        protected override void OnSourceInitialized(EventArgs e)
        {
   
            base.OnSourceInitialized(e);

            _windowHandle = new WindowInteropHelper(this).Handle;
            _source = HwndSource.FromHwnd(_windowHandle);
            _source.AddHook(HwndHook);

            RegisterHotKey(_windowHandle, HOTKEY_ID, 0, 0x73); 
            //_windowHandle: 窗口句柄,当触发热键时,会被该窗口接收系统生成的消息
            //HOTKEY_ID: 热键id
            /*0: 组合键, 0代表不使用组合键,还可以是以下的值
            private const uint MOD_NONE = 0x0000; //[NONE]
			private const uint MOD_ALT = 0x0001; //ALT
			private const uint MOD_CONTROL = 0x0002; //CTRL
			pri
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值