在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 小时前
浏览器中的隐藏IDE: Elements (元素) 面板
开发语言·前端·ide·php
DKPT1 小时前
JVM栈溢出和堆溢出哪个先满?
java·开发语言·jvm·笔记·学习
gopyer5 小时前
180课时吃透Go语言游戏后端开发6:Go语言的循环语句
开发语言·游戏·golang·循环语句
楼田莉子7 小时前
Qt开发学习——QtCreator深度介绍/程序运行/开发规范/对象树
开发语言·前端·c++·qt·学习
韩立学长8 小时前
【开题答辩实录分享】以《基于python的奶茶店分布数据分析与可视化》为例进行答辩实录分享
开发语言·python·数据分析
天若有情6738 小时前
C++空值初始化利器:empty.h使用指南
开发语言·c++
远远远远子8 小时前
类与对象 --1
开发语言·c++·算法
无敌最俊朗@9 小时前
C/C++ 关键关键字面试指南 (const, static, volatile, explicit)
c语言·开发语言·c++·面试
2401_831501739 小时前
Python学习之day03学习(文件和异常)
开发语言·python·学习
酷~9 小时前
C语言模拟面向对象编程方法之多态
c语言·开发语言