此 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中文网其他相关文章!