在WPF應用程式中使用.NET Framework 3.5註冊全域熱鍵
挑戰:
在使用.NET Framework 3.5開發的WPF應用程式中,您需要一種方法來綁定到特定按鍵,並決定如何綁定到Windows鍵。
解:
要在WPF和.NET Framework 3.5中註冊全域熱鍵,請執行下列步驟:
<code class="language-csharp">using System; using System.Runtime.InteropServices; using System.Windows.Interop;</code>
<code class="language-csharp">[DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, UInt32 fsModifiers, UInt32 vlc); [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); const int WmHotKey = 0x0312;</code>
<code class="language-csharp">public class HotKey : IDisposable { private bool _disposed; private Key _key; private KeyModifier _keyModifiers; private Action<HotKey> _action; private int _id; private static Dictionary<int, HotKey> _dictHotKeyToCalBackProc; public HotKey(Key k, KeyModifier keyModifiers, Action<HotKey> action, bool register = true) { _key = k; _keyModifiers = keyModifiers; _action = action; if (register) Register(); } public bool Register() { int virtualKeyCode = KeyInterop.VirtualKeyFromKey(_key); _id = virtualKeyCode + ((int)_keyModifiers * 0x10000); bool result = RegisterHotKey(IntPtr.Zero, _id, (UInt32)_keyModifiers, (UInt32)virtualKeyCode); if (_dictHotKeyToCalBackProc == null) { _dictHotKeyToCalBackProc = new Dictionary<int, HotKey>(); ComponentDispatcher.ThreadFilterMessage += ComponentDispatcherThreadFilterMessage; } _dictHotKeyToCalBackProc.Add(_id, this); return result; } public void Unregister() { _dictHotKeyToCalBackProc.Remove(_id); UnregisterHotKey(IntPtr.Zero, _id); } private static void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled) { if (msg.message == WmHotKey) { HotKey hotKey; if (_dictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey)) { hotKey._action.Invoke(hotKey); handled = true; } } } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { Unregister(); } _disposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } }</code>
<code class="language-csharp">// 注册CTRL+SHIFT+F9热键 HotKey hotKey = new HotKey(Key.F9, KeyModifier.Shift | KeyModifier.Ctrl, OnHotKeyHandler); private void OnHotKeyHandler(HotKey hotKey) { // 按下热键时执行操作 }</code>
這段程式碼對原文進行了細微的調整,使其更流暢易讀,並修正了一些潛在問題,例如在Unregister
方法中增加了從字典中移除熱鍵的邏輯,以及完善了Dispose
方法以確保資源的正確釋放。 關鍵的邏輯和程式碼保持不變,實現了對原文的偽原創。
以上是如何使用 .NET Framework 3.5 在 WPF 應用程式中註冊全域熱鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!