TXTReader功能之一:HotKey

首先,引用using System.Runtime.InteropServices;

using System.Runtime.InteropServices;

其次,声明API函数,分别为RegisterHotKey(注册热键)和UnregisterHotKey(卸载热键)

[DllImport("user32.dll")]
public static extern bool RegisterHotKey(
       IntPtr hWnd, //handle to winfow
       int id, //hot key identifer
       uint fsModifiers, // key-modifier options
       Keys vk //virtual-key code
       );

[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(
        IntPtr hWnd, //handle to winfow
        int id //hot key identifer
        );

然后,定义枚举

public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }

之后,重写WndProc事件,并定义相应的点击事件

protected override void WndProc(ref Message m)
{
    //如果m.Msg的值为0x0312,则表示用户按下了热键
    const int WM_HOTKEY = 0x0312;
    switch (m.Msg)
    {
        case WM_HOTKEY:
            ProcessHotKey(m);
            break;
    }

     base.WndProc(ref m);
}

最后,在Form加载页面或者构造函数中根据需求注册热键,在关闭Form之前卸载热键,即可。

public Form2()
{
   InitializeComponent();

   //注册HotKey
   RegisterHotKey(Handle, 100, 1, Keys.D1);//Alt + 1
   RegisterHotKey(Handle, 200, 1, Keys.D2);//Alt + 2
   RegisterHotKey(Handle, 300, 2, Keys.D2);//Control + 2
}

private void Form2_BeforeClose(object sender, FormClosingEventArgs e)
{
    UnregisterHotKey(Handle, 100);
    UnregisterHotKey(Handle, 200);
    UnregisterHotKey(Handle, 300);
}

编写时主要参考了这篇博客——C# WinForm程序中使用热键(HotKey)_代码世界-CSDN博客_winform 系统热键

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值