本文最后更新于 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();