C# の RegisterHotKey を使用したホットキー登録の実装方法

C#では、User32.dllライブラリにあるRegisterHotKey関数を用いてホットキーを登録できます。以下に例を示します。

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class HotKeyManager
{
    [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;

    public static event EventHandler<HotKeyEventArgs> HotKeyPressed;

    public static void RegisterHotKey(Keys key, KeyModifiers modifiers)
    {
        int id = key.GetHashCode();
        RegisterHotKey(IntPtr.Zero, id, (uint)modifiers, (uint)key);
    }

    public static void UnregisterHotKey(Keys key, KeyModifiers modifiers)
    {
        int id = key.GetHashCode();
        UnregisterHotKey(IntPtr.Zero, id);
    }

    public static void ProcessHotKey(Message message)
    {
        if (message.Msg == WM_HOTKEY)
        {
            Keys key = (Keys)(((int)message.LParam >> 16) & 0xFFFF);
            KeyModifiers modifiers = (KeyModifiers)((int)message.LParam & 0xFFFF);
            HotKeyPressed?.Invoke(null, new HotKeyEventArgs(key, modifiers));
        }
    }
}

class HotKeyEventArgs : EventArgs
{
    public Keys Key { get; private set; }
    public KeyModifiers Modifiers { get; private set; }

    public HotKeyEventArgs(Keys key, KeyModifiers modifiers)
    {
        Key = key;
        Modifiers = modifiers;
    }
}

[Flags]
enum KeyModifiers
{
    None = 0,
    Alt = 1,
    Control = 2,
    Shift = 4,
    Windows = 8
}

class Program : Form
{
    public Program()
    {
        HotKeyManager.RegisterHotKey(Keys.F1, KeyModifiers.Control);
        HotKeyManager.HotKeyPressed += HotKeyManager_HotKeyPressed;
    }

    private void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
    {
        if (e.Key == Keys.F1 && e.Modifiers == KeyModifiers.Control)
        {
            Console.WriteLine("Hotkey pressed: " + e.Key.ToString() + " + " + e.Modifiers.ToString());
        }
    }

    protected override void WndProc(ref Message message)
    {
        HotKeyManager.ProcessHotKey(message);
        base.WndProc(ref message);
    }

    static void Main(string[] args)
    {
        Application.Run(new Program());
    }
}

上記のサンプルでは、まずHotKeyManagerというクラスを定義しており、このクラスはuser32.dllライブラリ内のRegisterHotKey、UnregisterHotKey関数を使用してホットキーを登録、登録解除します。このクラスは、ホットキーイベントを処理するためのHotKeyPressedイベントとHotKeyEventArgsクラスも定義しています。

Programクラスのコンストラクタ内において、ホットキー(Ctrl + F1)を登録し、HotKeyPressedイベントを購読しています。ホットキーが押下されると、HotKeyManager_HotKeyPressedメソッドが呼び出されます。

WndProcメソッド内で、ホットキーメッセージを処理するためにHotKeyManagerクラスのProcessHotKeyメソッドを呼び出すことになります。

最後に、Mainメソッドでは、Formを継承したWindowsフォームアプリケーションを実行しており、そのコンストラクタにてProgramインスタンスを作成しています。

プログラムを実行後、Ctrl + F1キーを押下すると、コンソールに「Hotkey pressed: F1 + Control」と出力されます。

bannerAds