Home >Backend Development >C++ >How to Set Global Hotkeys in C# Using Win32 API?

How to Set Global Hotkeys in C# Using Win32 API?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-24 05:36:13944browse

How to Set Global Hotkeys in C# Using Win32 API?

C# Global Hotkey Setting Guide

Global hotkeys allow you to capture keystrokes even when the program is not in focus. This is useful for implementing shortcut keys or performing specific actions triggered by key combinations. Below are detailed instructions for setting global hotkeys using C#.

Create a hotkey handling class

First, create a class named KeyboardHook to handle registering and capturing hotkeys:

<code class="language-csharp">public sealed class KeyboardHook : IDisposable
{
    // 导入必要的Win32 API函数
    [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 class Window : NativeWindow, IDisposable
    {
        ...
        // 处理Win32热键消息
        protected override void WndProc(ref Message m)
        {
            ...
            // 调用事件以通知父级
            if (KeyPressed != null)
                KeyPressed(this, new KeyPressedEventArgs(modifier, key));
        }
    }

    private Window _window = new Window();
    private int _currentId;

    // 注册热键
    public void RegisterHotKey(ModifierKeys modifier, Keys key)
    {
        ...
        // 注册热键
        if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
            throw new InvalidOperationException("无法注册热键。");
    }
}</code>

Register hotkeys

Instantiate the KeyboardHook class and use its RegisterHotKey methods to register the desired hotkey combination. For example, to register the Ctrl, Alt and F12 keys as hotkeys:

<code class="language-csharp">hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt, Keys.F12);</code>

Handling hotkey events

To execute code when a hotkey is pressed, subscribe to the KeyboardHook event of class KeyPressed:

<code class="language-csharp">hook.KeyPressed += new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);</code>

In an event handler you can perform any action or logic you want.

Logout Hotkey

To prevent memory leaks, be sure to log out hotkeys when the program exits or when the hotkeys are no longer needed:

<code class="language-csharp">hook.Dispose();</code>

Important Tips

  • This technique requires a Windows Forms project, not a console application project.
  • Avoid using the NativeWindow class in multi-threaded environments without appropriate synchronization mechanisms.
  • RegisterHotKey Functions There is a limit of 256 hotkey combinations per application.

The above is the detailed content of How to Set Global Hotkeys in C# Using Win32 API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn