温馨提示×

C#中RegisterHotKey注册热键怎么实现

c#
小亿
83
2023-12-07 02:56:41
栏目: 编程语言

在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方法中,我们运行了一个Windows窗体应用程序,该窗体继承自Form,并在构造函数中创建了一个Program实例。

运行程序后,按下Ctrl + F1键,控制台会输出"Hotkey pressed: F1 + Control"。

0