Home >Backend Development >C++ >How to Capture Global Hotkeys in C#?
Capturing global hotkeys in C#
In C#, capturing keystrokes even when the program is not in focus requires special handling. This article will guide you through the process of setting global hotkeys so that your program responds to key combinations even when other windows are active.
Use platform call
In order to interact with the Windows operating system, C# uses platform calls (DllImport). The following DLL functions are essential for setting hotkeys:
Create keyboard hook class
To handle global hotkeys, create a KeyboardHook class that inherits from IDisposable:
<code class="language-csharp">public sealed class KeyboardHook : IDisposable { // ... }</code>
In this class, you need to create a nested Window class to receive hotkey messages:
<code class="language-csharp">private class Window : NativeWindow, IDisposable { // ... }</code>
Register hotkeys
To register a hotkey, use the RegisterHotKey method in the KeyboardHook class:
<code class="language-csharp">public void RegisterHotKey(ModifierKeys modifier, Keys key) { // ... }</code>
This method will increment an internal counter (_currentId) and then register the hotkey with Windows using the specified modifier and key.
Responds to hotkey presses
When a hotkey is pressed, the event handler KeyPressed is fired. You can subscribe to this event in your main application and perform the desired action when the hotkey is triggered.
Example usage
In the provided example, a form with a label is created to display the pressed keys:
<code class="language-csharp">public partial class Form1 : Form { // ... }</code>
In the form's constructor, create a KeyboardHook instance and register the hotkey combinations for Control, Alt, and F12:
<code class="language-csharp">hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt, Keys.F12);</code>
When a hotkey is pressed, the hook_KeyPressed event handler is called and the label is updated with the modifier and key pressed.
The above is the detailed content of How to Capture Global Hotkeys in C#?. For more information, please follow other related articles on the PHP Chinese website!