WPF 热键
本文最后更新于 212 天前,其中的信息可能已经有所发展或是发生改变。
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Input;
using System.Windows.Interop;

public delegate void HotKeyCallback(HotKey hotKey);

public class HotKey
{
    private const int WM_HOTKEY = 0x0312;

    [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);

    static HotKey() => ComponentDispatcher.ThreadFilterMessage += ThreadFilterMessage;

    public HotKey(ModifierKeys modifierKeys, Key key) => (ModifierKeys, Key) = (modifierKeys, key);

    private static readonly Dictionary<int, HotKey> map = new();

    private int id;

    public ModifierKeys ModifierKeys { get; }
    public Key Key { get; }

    public event HotKeyCallback? Pressed;

    public static HotKey Create(ModifierKeys modifierKeys, Key key, HotKeyCallback? callback = null, bool register = true)
    {
        HotKey hotKey = new(modifierKeys, key);
        hotKey.Pressed += callback;
        if (register) hotKey.Register();
        return hotKey;
    }

    public bool Register()
    {
        int virtualKey = KeyInterop.VirtualKeyFromKey(Key);
        id = (int)ModifierKeys << 16 | virtualKey;
        bool result = RegisterHotKey(IntPtr.Zero, id, (uint)ModifierKeys, (uint)virtualKey);
        if (result) map.Add(id, this);
        return result;
    }

    public bool Unregister()
    {
        bool result = UnregisterHotKey(IntPtr.Zero, id);
        if (result) map.Remove(id);
        return result;
    }

    private static void ThreadFilterMessage(ref MSG msg, ref bool handled)
    {
        if (!handled)
        {
            if (msg.message == WM_HOTKEY)
            {
                if (map.TryGetValue((int)msg.wParam, out var hotKey))
                {
                    hotKey.Pressed?.Invoke(hotKey);
                    handled = true;
                }
            }
        }
    }
}

使用

快速上手

HotKey.Create(ModifierKeys.Control, Key.H, _ => MessageBox.Show("Hello!"));

使用 JSON

var hotKey = JsonSerializer.Deserialize<HotKey>("{\"ModifierKeys\":2,\"Key\":51}");
hotKey.Pressed += _ => MessageBox.Show("Hello!");
hotKey.Register();
作者:AlexSJC
本文采用 CC BY-NC-ND 4.0 许可协议
暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇