由于最近在做 wpf 版的截图软件, 在处理全局热键的时候, 发现国内博客使用的都是 winform 窗体的键盘处理方式, 此方式需要使用 winform 的动态库, 如此不协调的代码让我开始在 GitHub 中寻找相关代码.
最终, 我找到了, wpf 本身就支持处理系统的键盘消息 (包括热键).
使用 ComponentDispatcher 类处理键盘消息
下面贴上代码, 方便大家复制粘贴:
- public static class HotkeyListener
- {
- /// <summary>
- /// 热键消息
- /// </summary>
- const int WindowsMessageHotkey = 786;
- /// <summary>
- /// demo 的实例句柄
- /// </summary>
- public static IExcuteHotKey Instance = null;
- static HotkeyListener()
- {
- // 注册热键 (调用 Windows API 实现, 与 winform 一致)
- Hotkey hotkey = new Hotkey(Keys.F2, Modifiers.None, true);
- // 处理热键消息 (使用 wpf 的键盘处理)
- ComponentDispatcher.ThreadPreprocessMessage += (ref MSG Message, ref bool Handled) =>
- {
- // 判断是否热键消息
- if (Message.message == WindowsMessageHotkey)
- {
- // 获取热键 id
- var id = Message.wParam.ToInt32();
- // 执行热键回调方法 (执行时需要判断是否与注册的热键匹配)
- Instance.ExcuteHotKeyCommand(id);
- }
- };
- }
- }
关于 ComponentDispatcher 的说明
来源: https://www.cnblogs.com/zhuxiaoxiao/p/11420359.html