WPF无边框窗口的快捷建绑定方法

该代码示例展示了如何在C#中使用Win32API注册和注销快捷键。通过`RegisterHotKey`和`UnregisterHotKey`方法,结合`HotkeyModifiers`枚举定义组合键,当快捷键被按下时,会触发指定的回调函数执行相应操作。
摘要由CSDN通过智能技术生成
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Hotkey.Regist(this, HotkeyModifiers.MOD_ALT, Key.X, () =>
        {
        //快捷键对应的动作代码
        });
    }
}
static class Hotkey
{
    #region 系统api
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool RegisterHotKey(IntPtr hWnd, int id, HotkeyModifiers fsModifiers, uint vk);

    [DllImport("user32.dll")]
    static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    #endregion

    // <param name="callBack">回调函数</param>
    public static void Regist(Window window, HotkeyModifiers fsModifiers, Key key, HotKeyCallBackHanlder callBack)
    {
        var hwnd = new WindowInteropHelper(window).Handle;
        var _hwndSource = HwndSource.FromHwnd(hwnd);
        _hwndSource.AddHook(WndProc);

        int id = keyid++;

        var vk = KeyInterop.VirtualKeyFromKey(key);
        if (!RegisterHotKey(hwnd, id, fsModifiers, (uint)vk))
            throw new Exception("regist hotkey fail.");
        keymap[id] = callBack;
    }

    /// <summary> 
    /// 快捷键消息处理 
    /// </summary> 
    static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_HOTKEY)
        {
            int id = wParam.ToInt32();
            if (keymap.TryGetValue(id, out var callback))
            {
                callback();
            }
        }
        return IntPtr.Zero;
    }
    /// <summary> 
    /// 注销快捷键 
    /// </summary> 
    /// <param name="hWnd">持有快捷键窗口的句柄</param> 
    /// <param name="callBack">回调函数</param> 
    public static void UnRegist(IntPtr hWnd, HotKeyCallBackHanlder callBack)
    {
        foreach (KeyValuePair<int, HotKeyCallBackHanlder> var in keymap)
        {
            if (var.Value == callBack)
                UnregisterHotKey(hWnd, var.Key);
        }
    }


    const int WM_HOTKEY = 0x312;
    static int keyid = 10;
    static Dictionary<int, HotKeyCallBackHanlder> keymap = new Dictionary<int, HotKeyCallBackHanlder>();
    public delegate void HotKeyCallBackHanlder();
}

enum HotkeyModifiers
{
    MOD_ALT = 0x1,
    MOD_CONTROL = 0x2,
    MOD_SHIFT = 0x4,
    MOD_WIN = 0x8
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值