在C#中,可以使用user32.dll庫中的RegisterHotKey函數(shù)來注冊熱鍵。以下是一個示例:
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函數(shù)來注冊和注銷熱鍵。它還定義了HotKeyPressed事件和HotKeyEventArgs類來處理熱鍵事件。
在Program類的構(gòu)造函數(shù)中,我們注冊了一個熱鍵(Ctrl + F1),并訂閱了HotKeyPressed事件。當(dāng)熱鍵被按下時,HotKeyManager_HotKeyPressed方法會被調(diào)用。
在程序的WndProc方法中,我們調(diào)用HotKeyManager類的ProcessHotKey方法來處理熱鍵消息。
最后,在Main方法中,我們運行了一個Windows窗體應(yīng)用程序,該窗體繼承自Form,并在構(gòu)造函數(shù)中創(chuàng)建了一個Program實例。
運行程序后,按下Ctrl + F1鍵,控制臺會輸出"Hotkey pressed: F1 + Control"。