Set global hotkeys using C# to trigger events (even if the app is not in focus)
This article describes how to set global hotkeys in C# so that events can be triggered even if the application is not in focus.
Question:
Capture keystrokes when the program is not in focus (e.g. Ctrl Alt J) to trigger events within the program.
Solution:
Warning: This code will not trigger events in the console application. Please use WinForms project to implement event functionality.
Custom keyboard hook class:
<code class="language-csharp">public sealed class KeyboardHook : IDisposable { private Window _window = new Window(); private int _currentId; public KeyboardHook() { // ... // 按键事件处理 // ... } public void RegisterHotKey(ModifierKeys modifier, Keys key) { // ... // 通过内部原生窗口注册热键 // ... } public event EventHandler<KeyPressedEventArgs> KeyPressed; }</code>
Window class for event handling:
<code class="language-csharp">private class Window : NativeWindow, IDisposable { // ... protected override void WndProc(ref Message m) { // 处理热键按下 if (m.Msg == WM_HOTKEY) { // ... // 从LParam中提取修饰符和键 // ... // 触发KeyPressed事件 KeyPressed?.Invoke(this, new KeyPressedEventArgs(modifier, key)); } } // ... }</code>
Usage example:
<code class="language-csharp">public partial class Form1 : Form { private KeyboardHook hook = new KeyboardHook(); public Form1() { // ... hook.KeyPressed += hook_KeyPressed; //订阅事件 hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt, Keys.F12); // ... } void hook_KeyPressed(object sender, KeyPressedEventArgs e) { // 处理按键事件 } }</code>
Note:
(ModifierKeys)1
, (ModifierKeys)2
, etc. The above is the detailed content of How Can I Set Global Hotkeys in C# to Trigger Events Even When My Application Is Not in Focus?. For more information, please follow other related articles on the PHP Chinese website!