阅读量:2
在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
方法来处理该消息。