1. 在类内部声明两个API函数
[DllImport("user32.dll")] //在类内部声明两个API函数 public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys keys); [DllImport("user32.dll")] //在类内部声明两个API函数 public static extern bool UnregisterHotKey(IntPtr hWnd, int id); public static int WmHotkey = 0x0312; //标示用户按下了热键
2. 系统启动时注册基本事件
//系统启动时注册基本事件 protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); IntPtr hWnd = new WindowInteropHelper(this).Handle; RegisterHotKey(hWnd, 123, 0, Keys.F); //注册热键 var source = PresentationSource.FromVisual(this) as HwndSource; //获取内容 if (source != null) source.AddHook(WndProc); //注册处理方法 }
3. 编写获取热键时处理方法
//热键处理 重写WndProc()方法,通过监视系统消息,来调用过程 private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg != WmHotkey) return IntPtr.Zero; if (wParam.ToInt32() == 123) { ButtonBase_OnClick(null, null); handled=true; } return IntPtr.Zero; }
4. 系统关闭时注销热键
//软件关闭时注销热键 void Window1_Closed(object sender, EventArgs e) { IntPtr hWnd = new WindowInteropHelper(this).Handle; UnregisterHotKey(hWnd, 123); }
注:
组合键注释:
None = 0,
Alt = 1,
Control = 2,
Shift =
4,
Windows = 8
注册方法参数说明:
hwnd: handle to window
id: hot key identifier 热键标示
control:
key-modifier options 用于接收组合键
keys: virtual-key code
热键
原文:http://www.cnblogs.com/Alf7/p/3577058.html