由於最近在做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的說明

