C#中注册热键
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace Gkill { class RegistHotkey { IntPtr hwnd; //获取窗口句柄 [DllImport("user32.dll", EntryPoint = "FindWindow")] private extern static IntPtr FindWindow(string lpClassName, string lpWindowName); //注册全局热键 [DllImport("user32.dll")] private static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk); //删除全局热键 [DllImport("user32.dll")] private static extern int UnregisterHotKey(IntPtr hwnd, int id); private const int WM_HOTKEY = 0x312; //窗口消息-热键 private const int WM_CREATE = 0x1; //窗口消息-创建 private const int WM_DESTROY = 0x2; //窗口消息-销毁 private const int MOD_ALT = 0x1; //ALT private const int MOD_CONTROL = 0x2; //CTRL private const int MOD_SHIFT = 0x4; //SHIFT private const int VK_SPACE = 0x20; //SPACE public RegistHotkey() { hwnd = FindWindow(null,"Gki"); } public bool RegKey(int id, int fsModifiers, int vk) { if (RegisterHotKey(hwnd, id, fsModifiers, vk) == 0) { return false; } else { return true; } } public bool UnRegKey(int id) { if (UnregisterHotKey(hwnd, id) == 0) { return false; } else { return true; } } } }
private void RegistHotKey() { RegistHotkey hotkey = new RegistHotkey(); //displayHotkey hotkey.RegKey(100, 0x2, (int)Keys.O); //hideHotkey hotkey.RegKey(200, 0x2, (int)Keys.P); } protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x312://WM_HOTKEY:0x312 MessageBox.Show("有热键按下!但不知道是谁"); switch (m.WParam.ToInt32()) { case (100): this.Visible=true; this.Activate(); break; case (200): this.Visible = false; break; default: break; } break; case 0x1://WM_CREATE:0x1 break; case 0x2://WM_DESTROY:0x2 break; } base.WndProc(ref m); //将系统消息传递自父类的WndProc }