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

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

Patricia Arquette
發布: 2025-01-24 05:36:13
原創
943 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板