在C#中设置全局热键
当程序最小化或处于非活动状态时,您可能需要捕获特定的按键来触发操作。本文介绍如何在C#中注册全局热键,以便即使应用程序不是活动窗口,也能在应用程序中执行事件。
解决方案:
为了捕获与活动应用程序无关的热键,我们可以使用Win32 API函数RegisterHotKey
和UnregisterHotKey
。这些函数与Windows的系统级热键基础结构交互。
代码实现:
提供的代码使用一个专用的类KeyboardHook
,它封装了热键注册和事件处理功能。
<code class="language-csharp">public sealed class KeyboardHook : IDisposable { // 使用Windows注册热键。 [DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); // 使用Windows注销热键。 [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); ... }</code>
使用方法:
<code class="language-csharp">// 注册Control + Alt + F12热键组合。 hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt, Keys.F12); // 按键事件处理程序。 void hook_KeyPressed(object sender, KeyPressedEventArgs e) { label1.Text = e.Modifier.ToString() + " + " + e.Key.ToString(); }</code>
重要说明:
This revised output maintains the image and its original format while rephrasing the text for improved clarity and flow. Key terms are also slightly altered to avoid exact duplication.
以上是如何在 C# 中设置全局热键以在应用程序最小化时触发操作?的详细内容。更多信息请关注PHP中文网其他相关文章!