当前位置:首页 > Windows程序 > 正文

005] C#如何绑定HotKey

2021-05-26 Windows程序

  由于某种需要,需要做一个控制鼠标在屏幕乱点的程序,运用C#的

[DllImport("user32.dll")]
      private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

  这个方法,我们可以实现控制鼠标的移动单双击等功能。

  但是实现之后你会发现当你启动了屏幕测试的时候,鼠标已经不受你的控制,因为鼠标到处乱跑,这个时候我想到了我们需要一个HotKey类似Ctrl + CCtrl + V这样的功能来让程序停止下来。下面就讲讲具体的实现方式。

  我的应用场景是WinForm,我们需要在窗口激活的时候去定义HotKey

private void Form1_Activated(object sender, EventArgs e) {   // 注册热键Ctrl+B,Id号为101。HotKey.KeyModifiers.Ctrl也可以直接使用数字2来表示。 Form1.RegisterHotKey(Handle, 100, Form1.KeyModifiers.Shift, Keys.S); Form1.RegisterHotKey(Handle, 101, Form1.KeyModifiers.Shift, Keys.E); }

  然后获取到注册了热键之后,,我们要怎么去注册热键的事件呢,我们需要重载WndProc方法

protected override void WndProc(ref Message m) {   const int WM_HOTKEY = 0x0312; // 按快捷键 switch (m.Msg) {   case WM_HOTKEY:   switch (m.WParam.ToInt32()) {   case 100:
          // 按钮点击 this.button1.PerformClick(); break; case 101: this.runFlag = false; if (clickThread != null) { clickThread.Abort(); } break; } break; } base.WndProc(ref m); }

  在程序关闭之后关闭热键,我们可以在Form_Closing事件进行关闭

private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // 注销Id号为100的热键设定 Form1.UnregisterHotKey(Handle, 100); // 注销Id号为101的热键设定   Form1.UnregisterHotKey(Handle, 101); }

  通过以上的三步我们就可以轻松的去定义热键了。

结语

受益,学会了如何在C#程序中定义热键

 

 

技术分享

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/71447.html