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

相关推荐
一个闪现必杀技2 分钟前
Python入门--函数
开发语言·python·青少年编程·pycharm
Fan_web5 分钟前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
龙图:会赢的9 分钟前
[C语言]--编译和链接
c语言·开发语言
XKSYA(小巢校长)2 小时前
NatGo我的世界联机篇
开发语言·php
Cons.W2 小时前
Codeforces Round 975 (Div. 1) C. Tree Pruning
c语言·开发语言·剪枝
憧憬成为原神糕手2 小时前
c++_ 多态
开发语言·c++
VBA63372 小时前
VBA信息获取与处理第三个专题第三节:工作薄在空闲后自动关闭
开发语言
wjs20243 小时前
XSLT 实例:掌握 XML 转换的艺术
开发语言
萧鼎3 小时前
Python第三方库选择与使用陷阱避免
开发语言·python
安冬的码畜日常3 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js