C# WinForm程序中使用热键(HotKey)

本文详细介绍如何在C# WinForm应用中注册和使用热键,包括导入必要库、声明API函数、定义枚举、注册热键、监听系统消息及处理热键事件,并给出完整示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先引入System.Runtime.InteropServices

1
using System.Runtime.InteropServices;

2、在类内部声明两个API函数,它们的位置和类的成员变量等同 。

1
2
3
4
5
6
7
8
9
10
11
12
13
System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数 
public static extern bool RegisterHotKey(
    IntPtr hWnd, // handle to window 
    int id, // hot key identifier 
    uint fsModifiers, // key-modifier options 
    Keys vk // virtual-key code 
); 
  
[System.Runtime.InteropServices.DllImport("user32.dll")] //申明API函数 
public static extern bool UnregisterHotKey(
    IntPtr hWnd, // handle to window 
    int id // hot key identifier 
);

3、定义一个KeyModifiers的枚举,以便出现组合键。

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

4、在类的构造函数出注册系统热键

示例,下例注册了四个热键:

1
2
3
4
5
6
7
8
9
10
11
public MainForm()
{
 InitializeComponent(); 
  
 RegisterHotKey(Handle, 100, 2, Keys.Left); // 热键一:Control +光标左箭头
 RegisterHotKey(Handle, 200, 2, Keys.Right); //热键一:Control +光标右箭头
 RegisterHotKey(Handle, 300, 2, Keys.Up); // 热键一:Control +光标上箭头
 RegisterHotKey(Handle, 400, 2, Keys.Down); // 热键一:Control +光标下箭头
  
 ....; 
}

5、重写WndProc()方法,通过监视系统消息,来调用过程。

示例:

1
2
3
4
5
6
7
8
9
10
11
protected override void WndProc(ref Message m)//监视Windows消息 
 const int WM_HOTKEY = 0x0312; //如果m.Msg的值为0x0312那么表示用户按下了热键 
 switch (m.Msg) 
 { 
  case WM_HOTKEY: 
  ProcessHotkey(m); //按下热键时调用ProcessHotkey()函数
  break
 } 
 base.WndProc(ref m); //将系统消息传递自父类的WndProc 
}

6、不用说,我们接下来需要实现ProcessHotkey函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//按下设定的键时调用该函数 
private void ProcessHotkey(Message m) 
{
 IntPtr id = m.WParam; //IntPtr用于表示指针或句柄的平台特定类型 
 //MessageBox.Show(id.ToString()); 
 string sid = id.ToString(); 
 switch (sid)
 {
  case "100": DecreseVolumnb(); break; // 按下Control +光标左箭头,调用函数DecreseVolumnb(); 
  case "200": AddVolumnb(); break; // 按下Control +光标右箭头,调用函数AddVolumnb()
  case "300":// 按下Control +光标上箭头,显示窗体
   this.Visible = true
   break
  case "400":// 按下Control +光标下箭头,隐藏窗体
   this.Visible = false
   break
 } 
}

很明显接下来分别实现函数DecreseVolumnb(); 和AddVolumnb(); 即可.

7、最后别忘了在程序退出时取消热键的注册

1
2
3
4
5
6
7
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
 UnregisterHotKey(Handle, 100); //卸载第1个快捷键 
 UnregisterHotKey(Handle, 200); //缷载第2个快捷键
 UnregisterHotKey(Handle, 300); //卸载第3个快捷键 
 UnregisterHotKey(Handle, 400); //缷载第4个快捷键
}

以上就是在C#程序中使用系统热键的详细过程,希望对你了解C# WinForm程序使用热键有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值