using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Rs.Framework { /// /// 热键管理类 /// public class HotKeyManager { private const int MOD_ALT = 0x0001; // Alt键 private const int MOD_CTRL = 0x0002; // Ctrl键 private const int MOD_SHIFT = 0x0004; // Shift键 private const int MOD_WIN = 0x0008; // Windows键 private const int WM_HOTKEY = 0x0312; private Action hotkeyAction; private int id; [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); public HotKeyManager(Keys key, int modifier, Action action) { hotkeyAction = action; id = this.GetHashCode(); RegisterHotKey(Application.OpenForms[0].Handle, id, modifier, key); Application.AddMessageFilter(new MessageFilter(this)); } public void Unregister() { UnregisterHotKey(Application.OpenForms[0].Handle, id); } private class MessageFilter : IMessageFilter { private HotKeyManager hotkey; public MessageFilter(HotKeyManager hotkey) { this.hotkey = hotkey; } public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_HOTKEY && (int)m.WParam == hotkey.id) { hotkey.hotkeyAction(null, EventArgs.Empty); return true; } return false; } } } }