在C#中,可以使用Windows API函數(shù)來注冊全局熱鍵。以下是一個示例代碼,演示如何注冊多個全局熱鍵:
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
類負責(zé)注冊和注銷全局熱鍵,并處理熱鍵事件。MainForm
類繼承自Form
,并使用HotkeyManager
來注冊三個全局熱鍵(A、B和C鍵)。在HotkeyManager_HotkeyPressed
方法中,可以根據(jù)熱鍵的ID執(zhí)行相應(yīng)的操作。
注意,在注冊熱鍵之前,需要先調(diào)用RegisterHotKey
函數(shù),傳入窗口的句柄、熱鍵ID、修改鍵和熱鍵鍵值。當熱鍵被按下時,系統(tǒng)將發(fā)送一個WM_HOTKEY
消息到窗口的消息隊列中,可通過重寫WndProc
方法來處理該消息。