在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.OpenForms0.Handle, id, modifier, key);

Application.AddMessageFilter(new MessageFilter(this));

}

public void Unregister()

{

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

相关推荐
彧azz3 小时前
图的存储结构详解:邻接矩阵的原理、实现与应用
开发语言·数据结构·学习·php
嵌入式学习菌4 小时前
Modbus‑RTU 数据类型分析
开发语言·单片机·bug
matlab代码5 小时前
基于matlab数字图像处理的指纹识别系统【源码68期】
开发语言·matlab
matlab代码5 小时前
基于matlab的水果识别系统(苹果香蕉菠萝梨桃子)【源码65期】
开发语言·matlab
wuyk5555 小时前
从零吃透 MQTT 通信|第 8 章 FreeRTOS 多任务架构下 MQTT 工程架构,任务拆分、队列解耦、临界区保护
c语言·开发语言·stm32·学习·架构
weixin199701080165 小时前
[特殊字符]《跨境二手ERP对接Back Market:标准化API + 7~10工作日技术合规审核实录》(附Python源码)
开发语言·python·pandas
尘客-追梦6 小时前
Day 01:插件化之前,先看清 ABI 这堵墙
开发语言·c++·qt
持敬chijing6 小时前
Python-数据类型-列表
开发语言·python·青少年编程
写后端的胖头鱼7 小时前
【高频面试题】Java 基础类型 + 包装类 + String 互相转换
java·开发语言
matlab代码8 小时前
基于matlab自助水果超市水果识别收费系统(GUI界面)【源码67期】
开发语言·matlab