由于最近在做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的说明