重写DefWndProc事件
#region Window 消息捕获 const int WM_COPYDATA = 0x004A; public struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; [MarshalAs(UnmanagedType.LPStr)] public string lpData; } [DllImport("user32")] public static extern bool ChangeWindowMessageFilter(uint msg, int flags); protected override void DefWndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { case WM_COPYDATA: COPYDATASTRUCT mystr = new COPYDATASTRUCT(); Type mytype = mystr.GetType(); mystr = (COPYDATASTRUCT)m.GetLParam(mytype); Trace(mystr.lpData); processCommand(mystr.lpData); break; default: base.DefWndProc(ref m); break; } //System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " " + m.Msg.ToString()); } #endregion Window 消息捕获
重写WndProc事件
//注册热键的api [DllImport("user32")] public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk); //解除注册热键的api [DllImport("user32")] public static extern bool UnregisterHotKey(IntPtr hWnd, int id); private frmHotkeyTest testFrm = null; private void ShowTestFrm(string _text) { testFrm = new frmHotkeyTest(); this.WindowState = FormWindowState.Maximized; this.TopMost = true; this.Show(); this.TopMost = false; testFrm.Text = _text; testFrm.ShowDialog(); } protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x0312: //这个是window消息定义的注册的热键消息 if (m.WParam.ToString() == "123") // 按下CTRL+Q隐藏 { testFrm = new frmHotkeyTest(); testFrm.ShowDialog(); } else if (m.WParam.ToString() == "456") // 按下CTRL+W显示 { testFrm.Close(); } else if (m.WParam.ToString() == "103") { ShowTestFrm("F5"); } else if (m.WParam.ToString() == "102") { ShowTestFrm("Ctrl+Alt+D"); } else if (m.WParam.ToString() == "101") { ShowTestFrm("Ctrl+B"); } else if (m.WParam.ToString() == "100") { ShowTestFrm("Shift+S"); } break; } base.WndProc(ref m); }
在回调WndProc方法中,根据消息编码判断各种快捷键回调处理即可
例如:
if (m.WParam.ToString() == "123") // 按下CTRL+Q隐藏