要在C#中注冊多個全局熱鍵,可以使用Windows API中的RegisterHotKey函數。以下是一個示例代碼,演示如何在C#中注冊多個全局熱鍵:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class HotKeyManager
{
// 導入Windows API中的RegisterHotKey函數
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
// 導入Windows API中的UnregisterHotKey函數
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
// 定義熱鍵的標識符
private const int HOTKEY_ID_1 = 1;
private const int HOTKEY_ID_2 = 2;
// 定義熱鍵的鍵值和修飾鍵
private const int HOTKEY_MODIFIER_1 = 0x0002; // Ctrl鍵
private const int HOTKEY_MODIFIER_2 = 0x0001; // Alt鍵
private const int HOTKEY_VK_1 = (int)Keys.F1;
private const int HOTKEY_VK_2 = (int)Keys.F2;
// 定義熱鍵的響應事件
public event EventHandler HotKeyPressed1;
public event EventHandler HotKeyPressed2;
public HotKeyManager(IntPtr hWnd)
{
// 注冊第一個熱鍵
RegisterHotKey(hWnd, HOTKEY_ID_1, HOTKEY_MODIFIER_1, HOTKEY_VK_1);
// 注冊第二個熱鍵
RegisterHotKey(hWnd, HOTKEY_ID_2, HOTKEY_MODIFIER_2, HOTKEY_VK_2);
// 注冊全局熱鍵消息的處理函數
ComponentDispatcher.ThreadPreprocessMessage += ThreadPreprocessMessage;
}
private void ThreadPreprocessMessage(ref MSG msg, ref bool handled)
{
if (handled)
return;
if (msg.message == WM_HOTKEY)
{
switch (msg.wParam.ToInt32())
{
case HOTKEY_ID_1:
// 觸發第一個熱鍵的事件
HotKeyPressed1?.Invoke(this, EventArgs.Empty);
handled = true;
break;
case HOTKEY_ID_2:
// 觸發第二個熱鍵的事件
HotKeyPressed2?.Invoke(this, EventArgs.Empty);
handled = true;
break;
}
}
}
public void UnregisterHotKeys(IntPtr hWnd)
{
// 注銷熱鍵
UnregisterHotKey(hWnd, HOTKEY_ID_1);
UnregisterHotKey(hWnd, HOTKEY_ID_2);
}
private const int WM_HOTKEY = 0x0312;
[StructLayout(LayoutKind.Sequential)]
private struct MSG
{
public IntPtr hwnd;
public int message;
public IntPtr wParam;
public IntPtr lParam;
public int time;
public POINT pt;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int X;
public int Y;
}
}
使用示例:
public partial class MainForm : Form
{
private HotKeyManager hotKeyManager;
public MainForm()
{
InitializeComponent();
hotKeyManager = new HotKeyManager(this.Handle);
hotKeyManager.HotKeyPressed1 += HotKeyManager_HotKeyPressed1;
hotKeyManager.HotKeyPressed2 += HotKeyManager_HotKeyPressed2;
}
private void HotKeyManager_HotKeyPressed1(object sender, EventArgs e)
{
// 第一個熱鍵被觸發時的處理邏輯
MessageBox.Show("第一個熱鍵被觸發");
}
private void HotKeyManager_HotKeyPressed2(object sender, EventArgs e)
{
// 第二個熱鍵被觸發時的處理邏輯
MessageBox.Show("第二個熱鍵被觸發");
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
hotKeyManager.UnregisterHotKeys(this.Handle);
}
}
在上述示例中,我們創建了一個HotKeyManager類來管理熱鍵的注冊和處理。通過調用RegisterHotKey函數注冊熱鍵,通過調用UnregisterHotKey函數注銷熱鍵。在HotKeyManager類中,我們使用ComponentDispatcher.ThreadPreprocessMessage事件來監聽全