1、封装一个热键辅助类
/// <summary> /// 热键辅助 /// </summary> internal static class HotKeyHelper { [DllImport("kernel32.dll")] public static extern uint GetLastError(); //如果函数执行成功,返回值不为0。 //如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。 [DllImport("user32.dll")] public static extern bool RegisterHotKey( IntPtr hwnd, //要定义热键的窗口的句柄 int id, //定义热键ID(不能与其它ID重复) HotKeyModifiers hotKeyModifiers, //标识热键是否在按Alt、Ctrl、Shift等键时才会生效 Keys vk //定义热键的内容 ); [DllImport("user32.dll", SetLastError = true)] public static extern bool UnregisterHotKey(IntPtr hwnd, int id); public const int WmHotKey = 0x312; //窗口消息-热键 public const int WmCreate = 0x1; //窗口消息-创建 public const int WmDestroy = 0x2; //窗口消息-销毁 [Flags()] public enum HotKeyModifiers { ModAlt = 0x1, ModControl = 0x2, ModShift = 0x4, ModWin = 0x8 } //快捷键ID /// <summary> /// 程序隐藏和呼出 /// </summary> public const int key0 = 0;//程序隐藏和呼出 /// <summary> /// 截图ocr /// </summary> public const int key1 = 1;//截图ocr }
这个类里面,我定义两个快捷键ID,一个是程序的呼出、一个是截图,接下来看看程序中怎么使用的:
2、主窗体代码中,重写窗体消息监控事件
/// <summary> /// 窗体消息监控 /// </summary> /// <param name="m">The m.</param> protected override void WndProc(ref Message m) { switch (m.Msg) { case HotKeyHelper.WmCreate: RegisterHotKey(); break; case HotKeyHelper.WmDestroy: UnRegisterHotKey(); break; case HotKeyHelper.WmHotKey: switch (m.WParam.ToInt32()) { case HotKeyHelper.key0: { //你的程序 显示与隐藏的逻辑 break; } case HotKeyHelper.key1: { //截图的逻辑 break; } } break; default: break; } try { base.WndProc(ref m); } catch { } }
2、快捷键注册和取消注册的方法
/// <summary> /// 注册热键,窗体句柄,热键ID,辅助键,实键 /// </summary> private void RegisterHotKey() { const HotKeyHelper.HotKeyModifiers hm = HotKeyHelper.HotKeyModifiers.ModControl | HotKeyHelper.HotKeyModifiers.ModShift; HotKeyHelper.RegisterHotKey(this.Handle, HotKeyHelper.key0, hm, Keys.G); HotKeyHelper.RegisterHotKey(this.Handle, HotKeyHelper.key1, hm, Keys.W); //if (success) //{ // //注册成功,如果失败,说明被占用,可以注册其他快捷键 // return; //} } /// <summary> /// 取消热键,程序退出时调用,窗体句柄,热键ID /// </summary> private void UnRegisterHotKey() { HotKeyHelper.UnregisterHotKey(this.Handle, HotKeyHelper.key0); HotKeyHelper.UnregisterHotKey(this.Handle, HotKeyHelper.key1); }
这里我将Ctrl+Shift+G注册为第一个热键、将Ctrl+Shift+W注册为第二个热键
留下您的脚步
最近评论