C# WinForm全局热键设置(整理)
-
概述
感觉网上文章整理的不全,我这边做个专栏,专门做这个事情吧,节省大家搜索、筛选、整理的时间精力。有用可以点个赞。转载请注明出处,谢谢。
-
代码:重写主窗体的WndProc方法
#region 系统热键注册(解决程序窗体不显示/不激活时会出现快捷键不生效的问题) private const int WM_CREATE = 0x1; //窗口消息-创建 private const int WM_DESTROY = 0x2; //窗口消息-销毁 private const int AltS_Id = 786; //Alt+S的消息id 可自定义 private const int AltC_Id = 787; //Alt+C的消息id 可自定义 /// <summary> /// 处理系统键盘消息 /// </summary> /// <param name="m">消息体</param> protected override void WndProc(ref Message m) { if (MouseButtons == MouseButtons.Right)//不响应非客户区域的右键 return; base.WndProc(ref m); switch (m.Msg) { case WM_CREATE: WinApi.HotKey.RegisterHotKey(this.Handle, AltS_Id, WinApi.HotKey.KeyModifiers.Alt, Keys.S); WinApi.HotKey.RegisterHotKey(this.Handle, AltC_Id, WinApi.HotKey.KeyModifiers.Alt, Keys.C); break; case WM_DESTROY: WinApi.HotKey.UnregisterHotKey(this.Handle, AltS_Id); WinApi.HotKey.UnregisterHotKey(this.Handle, AltC_Id); break; case AltS_Id: MainForm_KeyDown(null, new KeyEventArgs(Keys.Alt | Keys.S)); break; case AltC_Id: MainForm_KeyDown(null, new KeyEventArgs(Keys.Alt | Keys.C)); break; default: break; } } #endregion /// <summary> /// 监控快捷键 /// </summary> /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_KeyDown(object sender, KeyEventArgs e) { //Alt+S处理 if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.S) { //Code } //Alt+C处理 if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.C) { //Code } }
-
代码:热键Win32API
public class WinApi { /// <summary> /// 快捷键 /// </summary> public static class HotKey { //如果函数执行成功,返回值不为0。 //如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。 [DllImport("user32.dll", SetLastError = true)] public static extern bool RegisterHotKey( IntPtr hWnd, //要定义热键的窗口的句柄 int id, //定义热键ID(不能与其它ID重复) KeyModifiers fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效 Keys vk //定义热键的内容 ); [DllImport("user32.dll", SetLastError = true)] public static extern bool UnregisterHotKey( IntPtr hWnd, //要取消热键的窗口的句柄 int id //要取消热键的ID ); //定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值) [Flags()] public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 } } }