首頁 >後端開發 >C++ >如何使用 Win32 API 在 C# 中設定全域熱鍵?

如何使用 Win32 API 在 C# 中設定全域熱鍵?

Patricia Arquette
Patricia Arquette原創
2025-01-24 05:36:13944瀏覽

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

C#全域熱鍵設定指南

全域熱鍵可讓您即使在程式未處於焦點狀態時也能擷取按鍵。這對於實現快捷鍵或執行由按鍵組合觸發的特定操作非常有用。以下是使用C#設定全域熱鍵的詳細說明。

建立熱鍵處理類別

首先,建立一個名為KeyboardHook的類別來處理註冊和擷取熱鍵:

<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>

註冊熱鍵

實例化KeyboardHook類別並使用其RegisterHotKey方法註冊所需的熱鍵組合。例如,要註冊Ctrl、Alt和F12鍵作為熱鍵:

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

處理熱鍵事件

要在按下熱鍵時執行程式碼,請訂閱KeyboardHook類別的KeyPressed事件:

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

在事件處理程序中,您可以執行所需的任何操作或邏輯。

註銷熱鍵

為了防止記憶體洩漏,請確保在程式退出或不再需要熱鍵時註銷熱鍵:

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

重要提示

  • 此技術需要一個Windows窗體項目,而不是控制台應用程式項目。
  • 在沒有適當同步機制的多執行緒環境中,避免使用NativeWindow類別。
  • RegisterHotKey函數每個應用程式最多有256個熱鍵組合的限制。

以上是如何使用 Win32 API 在 C# 中設定全域熱鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn