温馨提示×

C# register global hotkey ,onekey 注册多个全局热键以及

c#
小亿
101
2023-12-19 08:57:57
栏目: 编程语言

在C#中,可以使用Windows API函数来注册全局热键。以下是一个示例代码,演示如何注册多个全局热键:

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

public class HotkeyManager
{
    private const int WM_HOTKEY = 0x0312;

    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, Keys vk);

    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    private IntPtr handle;
    private int currentId;

    public HotkeyManager(IntPtr handle)
    {
        this.handle = handle;
        currentId = 0;
    }

    public void RegisterHotkey(Keys key, KeyModifiers modifiers)
    {
        RegisterHotKey(handle, currentId, (int)modifiers, key);
        currentId++;
    }

    public void UnregisterHotkeys()
    {
        for (int i = 0; i < currentId; i++)
        {
            UnregisterHotKey(handle, i);
        }
    }

    public event Action<int> HotkeyPressed;

    protected virtual void OnHotkeyPressed(int id)
    {
        HotkeyPressed?.Invoke(id);
    }

    public void ProcessHotkeyMessage(Message m)
    {
        if (m.Msg == WM_HOTKEY)
        {
            int id = m.WParam.ToInt32();
            OnHotkeyPressed(id);
        }
    }
}

public enum KeyModifiers
{
    None = 0,
    Alt = 1,
    Ctrl = 2,
    Shift = 4,
    Win = 8
}

// Example usage:

public class MainForm : Form
{
    private HotkeyManager hotkeyManager;

    public MainForm()
    {
        hotkeyManager = new HotkeyManager(Handle);
        hotkeyManager.HotkeyPressed += HotkeyManager_HotkeyPressed;
        RegisterHotkeys();
    }

    private void RegisterHotkeys()
    {
        hotkeyManager.RegisterHotkey(Keys.A, KeyModifiers.None);
        hotkeyManager.RegisterHotkey(Keys.B, KeyModifiers.None);
        hotkeyManager.RegisterHotkey(Keys.C, KeyModifiers.None);
    }

    private void HotkeyManager_HotkeyPressed(int id)
    {
        Console.WriteLine("Hotkey pressed: " + id);
    }

    protected override void WndProc(ref Message m)
    {
        hotkeyManager.ProcessHotkeyMessage(m);
        base.WndProc(ref m);
    }
}

// Create and run the main form
Application.Run(new MainForm());

在上面的示例中,HotkeyManager类负责注册和注销全局热键,并处理热键事件。MainForm类继承自Form,并使用HotkeyManager来注册三个全局热键(A、B和C键)。在HotkeyManager_HotkeyPressed方法中,可以根据热键的ID执行相应的操作。

注意,在注册热键之前,需要先调用RegisterHotKey函数,传入窗口的句柄、热键ID、修改键和热键键值。当热键被按下时,系统将发送一个WM_HOTKEY消息到窗口的消息队列中,可通过重写WndProc方法来处理该消息。

0