在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`类负责在应用程序中全局注册和处理热键。

相关推荐
机器学习之心HML7 分钟前
MATLAB基于GWO-BP神经网络对某拨叉件锻造金属流动性的参数分析
开发语言·神经网络·matlab
Cg1362691597412 分钟前
多态的定义
java·开发语言
weixin_466813 分钟前
编程之python基础
开发语言·python
微信api接口介绍18 分钟前
微信社群管理开发
java·开发语言·网络·微信
csbysj202027 分钟前
PHP 类型比较
开发语言
William_cl40 分钟前
一、前置基础(MVC学习前提)_核心特性_【C# 泛型入门】为什么说 List<T>是程序员的 “万能收纳盒“?避坑指南在此
学习·c#·mvc
白熊18843 分钟前
【图像大模型】ms-swift 深度解析:一站式多模态大模型微调与部署框架的全流程使用指南
开发语言·ios·swift
qiuiuiu4132 小时前
正点原子RK3568学习日志6-驱动模块传参
linux·c语言·开发语言·单片机·学习
云闲不收2 小时前
golang的一些技巧
开发语言·后端·golang
凸头2 小时前
责任链模式
java·开发语言·责任链模式