ホームページ >バックエンド開発 >C++ >C# でグローバル ホットキーを設定して、アプリケーションがフォーカスされていない場合でもアプリケーション イベントをトリガーするにはどうすればよいですか?

C# でグローバル ホットキーを設定して、アプリケーションがフォーカスされていない場合でもアプリケーション イベントをトリガーするにはどうすればよいですか?

DDD
DDDオリジナル
2025-01-24 05:41:09145ブラウズ

この C# コードは、アプリケーションが最小化されている場合やフォーカスされていない場合でもイベントをトリガーするグローバル ホットキーを作成します。 理解を深めるために、説明とコードの明確さを改善しましょう。

How can I set global hotkeys in C# to trigger application events even when the application is not in focus?

C# でのグローバル ホットキーの作成

この記事では、C# でグローバル ホットキーを実装し、アプリケーションのフォーカスに関係なくキーボード ショートカットに応答する方法を説明します。 Ctrl Alt J などの組み合わせの登録と処理に焦点を当てます。

解決策: user32.dll

を使用する

これを達成するための鍵は、user32.dll ライブラリ、具体的には RegisterHotKey 関数と UnregisterHotKey 関数にあります。 これらの関数にはウィンドウ ハンドルが必要です。したがって、このソリューションは Windows フォーム アプリケーション (WinForms) に最適です。 コンソール アプリケーションには必要なウィンドウ コンテキストがありません。

コードの実装:

以下の改良されたコードは読みやすさを向上させ、包括的なコメントが含まれています:

<code class="language-csharp">using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public sealed class GlobalHotkey : IDisposable
{
    // Import necessary functions from user32.dll
    [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 const int WM_HOTKEY = 0x0312; // Windows message for hotkey events

    private readonly NativeWindow _window; // Internal window for message handling
    private int _hotKeyId; // Unique ID for each registered hotkey

    public GlobalHotkey()
    {
        _window = new NativeWindow();
        _window.AssignHandle(new CreateParams().CreateHandle()); // Create the window handle
        _window.WndProc += WndProc; // Assign the window procedure
    }

    // Registers a hotkey
    public void Register(ModifierKeys modifiers, Keys key)
    {
        _hotKeyId++; // Generate a unique ID
        if (!RegisterHotKey(_window.Handle, _hotKeyId, (uint)modifiers, (uint)key))
        {
            throw new Exception("Failed to register hotkey.");
        }
    }

    // Unregisters all hotkeys
    public void Unregister()
    {
        for (int i = 1; i <= _hotKeyId; i++)
        {
            UnregisterHotKey(_window.Handle, i);
        }
        _window.ReleaseHandle(); // Release the window handle
    }

    // Window procedure to handle hotkey messages
    private void WndProc(ref Message m)
    {
        if (m.Msg == WM_HOTKEY)
        {
            // Extract key and modifiers from message parameters
            Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
            ModifierKeys modifiers = (ModifierKeys)((int)m.LParam & 0xFFFF);

            // Raise the HotkeyPressed event
            HotkeyPressed?.Invoke(this, new HotkeyPressedEventArgs(modifiers, key));
        }
    }

    // Event fired when a registered hotkey is pressed
    public event EventHandler<HotkeyPressedEventArgs> HotkeyPressed;

    // IDisposable implementation
    public void Dispose()
    {
        Unregister();
        _window.Dispose();
    }
}

// Event arguments for HotkeyPressed event
public class HotkeyPressedEventArgs : EventArgs
{
    public ModifierKeys Modifiers { get; }
    public Keys Key { get; }

    public HotkeyPressedEventArgs(ModifierKeys modifiers, Keys key)
    {
        Modifiers = modifiers;
        Key = key;
    }
}

// Enum for hotkey modifiers
[Flags]
public enum ModifierKeys : uint
{
    None = 0,
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}</code>

使用例 (WinForms):

<code class="language-csharp">public partial class Form1 : Form
{
    private GlobalHotkey _globalHotkey;

    public Form1()
    {
        InitializeComponent();
        _globalHotkey = new GlobalHotkey();
        _globalHotkey.HotkeyPressed += GlobalHotkey_HotkeyPressed;
        _globalHotkey.Register(ModifierKeys.Control | ModifierKeys.Alt, Keys.J);
    }

    private void GlobalHotkey_HotkeyPressed(object sender, HotkeyPressedEventArgs e)
    {
        // Handle the hotkey press here
        MessageBox.Show($"Hotkey pressed: Ctrl+Alt+J");
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        _globalHotkey.Dispose(); // Important: Dispose of the hotkey when the form closes
        base.OnFormClosing(e);
    }
}</code>

リソースのリークを防ぐために、エラー処理を追加し、GlobalHotkey インスタンスを適切に破棄してください (OnFormClosing を参照)。 この改訂されたコードは、C# WinForms アプリケーションでグローバル ホットキーを管理するための、より堅牢でわかりやすいソリューションを提供します。

以上がC# でグローバル ホットキーを設定して、アプリケーションがフォーカスされていない場合でもアプリケーション イベントをトリガーするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。