c# 窗体 全局热键
时间: 2023-07-27 12:23:01 浏览: 60
在 C# 窗体中实现全局热键可以使用 Windows API 函数来实现。以下是一个示例代码:
```csharp
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class MainForm : Form
{
// 定义全局热键的 ID,可以为任意值,只要不重复即可
private const int HOTKEY_ID = 9000;
// 定义 Windows API 函数
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
// 定义热键的组合键和热键对应的键码
private const uint MOD_ALT = 0x0001;
private const uint VK_F1 = 0x70;
public MainForm()
{
InitializeComponent();
// 注册全局热键
RegisterHotKey(this.Handle, HOTKEY_ID, MOD_ALT, VK_F1);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
// 如果收到全局热键的消息
if (m.Msg == 0x0312 && m.WParam.ToInt32() == HOTKEY_ID)
{
Debug.WriteLine("Hotkey pressed");
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
// 注销全局热键
UnregisterHotKey(this.Handle, HOTKEY_ID);
}
}
```
在上面的示例中,我们定义了一个 `MainForm` 窗体,并在构造函数中注册了一个全局热键,热键的组合键为 Alt + F1,热键的 ID 为 9000。当用户按下热键时,我们会在控制台输出一条消息。
在窗体的 `WndProc` 方法中,我们判断收到的消息是否是全局热键的消息,如果是,就执行相应的操作。在窗体关闭时,我们需要注销全局热键,以释放资源。
需要注意的是,全局热键需要在 Windows 消息循环中进行注册和注销,因此必须在窗体中实现 `WndProc` 方法,并在其中处理相应的消息。同时,全局热键的组合键和热键对应的键码可以根据需求进行修改。