此 C# 程式碼建立一個全域熱鍵,即使應用程式最小化或未獲得焦點,該熱鍵也會觸發事件。 讓我們改進解釋和程式碼清晰度,以便更好地理解。
在 C# 中建立全域熱鍵
本文示範如何在 C# 中實現全域熱鍵,以響應鍵盤快捷鍵,而不管應用程式焦點如何。 我們將重點放在註冊和處理 Ctrl Alt J 等組合。
解:使用user32.dll
實現這一目標的關鍵在於 user32.dll
函式庫,特別是 RegisterHotKey
和 UnregisterHotKey
函數。 這些函數需要一個視窗句柄;因此,該解決方案最適合 Windows 窗體應用程式 (WinForms)。 控制台應用程式缺乏必要的視窗上下文。
程式碼實作:
下面改進的程式碼增強了可讀性並包含全面的註解:
<code class="language-csharp">using System; using System.Runtime.InteropServices; using System.Windows.Forms; public sealed class GlobalHotkey : IDisposable { // Import necessary functions from user32.dll [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); private const int WM_HOTKEY = 0x0312; // Windows message for hotkey events private readonly NativeWindow _window; // Internal window for message handling private int _hotKeyId; // Unique ID for each registered hotkey public GlobalHotkey() { _window = new NativeWindow(); _window.AssignHandle(new CreateParams().CreateHandle()); // Create the window handle _window.WndProc += WndProc; // Assign the window procedure } // Registers a hotkey public void Register(ModifierKeys modifiers, Keys key) { _hotKeyId++; // Generate a unique ID if (!RegisterHotKey(_window.Handle, _hotKeyId, (uint)modifiers, (uint)key)) { throw new Exception("Failed to register hotkey."); } } // Unregisters all hotkeys public void Unregister() { for (int i = 1; i <= _hotKeyId; i++) { UnregisterHotKey(_window.Handle, i); } _window.ReleaseHandle(); // Release the window handle } // Window procedure to handle hotkey messages private void WndProc(ref Message m) { if (m.Msg == WM_HOTKEY) { // Extract key and modifiers from message parameters Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); ModifierKeys modifiers = (ModifierKeys)((int)m.LParam & 0xFFFF); // Raise the HotkeyPressed event HotkeyPressed?.Invoke(this, new HotkeyPressedEventArgs(modifiers, key)); } } // Event fired when a registered hotkey is pressed public event EventHandler<HotkeyPressedEventArgs> HotkeyPressed; // IDisposable implementation public void Dispose() { Unregister(); _window.Dispose(); } } // Event arguments for HotkeyPressed event public class HotkeyPressedEventArgs : EventArgs { public ModifierKeys Modifiers { get; } public Keys Key { get; } public HotkeyPressedEventArgs(ModifierKeys modifiers, Keys key) { Modifiers = modifiers; Key = key; } } // Enum for hotkey modifiers [Flags] public enum ModifierKeys : uint { None = 0, Alt = 1, Control = 2, Shift = 4, Win = 8 }</code>
用法範例(WinForms):
<code class="language-csharp">public partial class Form1 : Form { private GlobalHotkey _globalHotkey; public Form1() { InitializeComponent(); _globalHotkey = new GlobalHotkey(); _globalHotkey.HotkeyPressed += GlobalHotkey_HotkeyPressed; _globalHotkey.Register(ModifierKeys.Control | ModifierKeys.Alt, Keys.J); } private void GlobalHotkey_HotkeyPressed(object sender, HotkeyPressedEventArgs e) { // Handle the hotkey press here MessageBox.Show($"Hotkey pressed: Ctrl+Alt+J"); } protected override void OnFormClosing(FormClosingEventArgs e) { _globalHotkey.Dispose(); // Important: Dispose of the hotkey when the form closes base.OnFormClosing(e); } }</code>
請記得新增錯誤處理並正確處置GlobalHotkey
實例(如OnFormClosing
所示)以防止資源外洩。 此修訂後的程式碼為管理 C# WinForms 應用程式中的全域熱鍵提供了更強大且易於理解的解決方案。
以上是如何在 C# 中設定全域熱鍵以觸發應用程式事件,即使應用程式未處於焦點狀態?的詳細內容。更多資訊請關注PHP中文網其他相關文章!