在C#中创建全局热键

在C#中创建全局热键通常涉及使用Windows提供的平台特定功能。在C#中,您可以使用Windows API的`RegisterHotKey`函数来创建全局热键。以下是如何创建全局热键的详细步骤:

using System;

using System.Runtime.InteropServices;

using System.Windows.Forms;

public class GlobalHotkey

{

private const int MOD_ALT = 0x0001; // Alt键

private const int MOD_CTRL = 0x0002; // Ctrl键

private const int MOD_SHIFT = 0x0004; // Shift键

private const int MOD_WIN = 0x0008; // Windows键

private const int WM_HOTKEY = 0x0312;

private Action<object, EventArgs> hotkeyAction;

private int id;

DllImport("user32.dll")

private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, Keys vk);

DllImport("user32.dll")

private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

public GlobalHotkey(Keys key, int modifier, Action<object, EventArgs> action)

{

hotkeyAction = action;

id = this.GetHashCode();

RegisterHotKey(Application.OpenForms[0].Handle, id, modifier, key);

Application.AddMessageFilter(new MessageFilter(this));

}

public void Unregister()

{

UnregisterHotKey(Application.OpenForms[0].Handle, id);

}

private class MessageFilter : IMessageFilter

{

private GlobalHotkey hotkey;

public MessageFilter(GlobalHotkey hotkey)

{

this.hotkey = hotkey;

}

public bool PreFilterMessage(ref Message m)

{

if (m.Msg == WM_HOTKEY && (int)m.WParam == hotkey.id)

{

hotkey.hotkeyAction(null, EventArgs.Empty);

return true;

}

return false;

}

}

}

下面是如何在Windows窗体应用程序中使用`GlobalHotkey`类来注册全局热键的示例:

using System;

using System.Windows.Forms;

public partial class MainForm : Form

{

public MainForm()

{

InitializeComponent();

// 注册全局热键 (Ctrl + F1) 并定义触发时要执行的操作

new GlobalHotkey(Keys.F1, GlobalHotkey.MOD_CTRL, (s, e) =>

{

MessageBox.Show("Ctrl + F1 被按下!");

});

}

}

在这个示例中,我们定义了一个`GlobalHotkey`类,该类封装了注册和处理全局热键的逻辑。我们在`MainForm`构造函数中注册热键,并指定触发热键时执行的操作。`GlobalHotkey`类负责在应用程序中全局注册和处理热键。

相关推荐
还在忙碌的吴小二1 小时前
Harness 最佳实践:Java Spring Boot 项目落地 OpenSpec + Claude Code
java·开发语言·spring boot·后端·spring
liliangcsdn1 小时前
mstsc不在“C:\Windows\System32“下在C:\windows\WinSxS\anmd64xxx“问题分析
开发语言·windows
小陈工1 小时前
2026年4月7日技术资讯洞察:下一代数据库融合、AI基础设施竞赛与异步编程实战
开发语言·前端·数据库·人工智能·python
KAU的云实验台1 小时前
【算法精解】AIR期刊算法IAGWO:引入速度概念与逆多元二次权重,可应对高维/工程问题(附Matlab源码)
开发语言·算法·matlab
会编程的土豆1 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
jerryinwuhan1 小时前
RDD第二次练习
开发语言·c#
wechat_Neal1 小时前
Golang的车载应用场景
开发语言·后端·golang
weixin_513449962 小时前
walk_these_ways项目学习记录第八篇(通过行为多样性 (MoB) 实现地形泛化)--策略网络
开发语言·人工智能·python·学习