Home >Backend Development >C++ >How Can I Set Global Hotkeys in C# to Trigger Actions Even When My Application is Minimized?

How Can I Set Global Hotkeys in C# to Trigger Actions Even When My Application is Minimized?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-24 05:32:17330browse

How Can I Set Global Hotkeys in C# to Trigger Actions Even When My Application is Minimized?

Set global hotkeys in C#

You may need to capture specific keystrokes to trigger actions when the program is minimized or inactive. This article describes how to register global hotkeys in C# so that events can be performed in an application even if the application is not the active window.

Solution:

In order to capture hotkeys that are not related to the active application, we can use the Win32 API functions RegisterHotKey and UnregisterHotKey. These functions interact with Windows' system-level hotkey infrastructure.

Code implementation:

The provided code uses a dedicated class KeyboardHook that encapsulates hotkey registration and event handling functionality.

<code class="language-csharp">public sealed class KeyboardHook : IDisposable
{
    // 使用Windows注册热键。
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
    // 使用Windows注销热键。
    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    ...
}</code>

Usage:

<code class="language-csharp">// 注册Control + Alt + F12热键组合。
hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt, Keys.F12);

// 按键事件处理程序。
void hook_KeyPressed(object sender, KeyPressedEventArgs e)
{
    label1.Text = e.Modifier.ToString() + " + " + e.Key.ToString();
}</code>

Important Note:

  • This solution requires a WinForms project to trigger events.
  • Certain modifiers, such as "Win" and "Shift", may require casts due to differences in enumeration values ​​between the C# and Win32 APIs.

This revised output maintains the image and its original format while rephrasing the text for improved clarity and flow. Key terms are also slightly altered to avoid exact duplication.

The above is the detailed content of How Can I Set Global Hotkeys in C# to Trigger Actions Even When My Application is Minimized?. 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