Sage.WindowsHotKey 1.0.0.1

dotnet add package Sage.WindowsHotKey --version 1.0.0.1
                    
NuGet\Install-Package Sage.WindowsHotKey -Version 1.0.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sage.WindowsHotKey" Version="1.0.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sage.WindowsHotKey" Version="1.0.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Sage.WindowsHotKey" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Sage.WindowsHotKey --version 1.0.0.1
                    
#r "nuget: Sage.WindowsHotKey, 1.0.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Sage.WindowsHotKey@1.0.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Sage.WindowsHotKey&version=1.0.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Sage.WindowsHotKey&version=1.0.0.1
                    
Install as a Cake Tool

Sage.WindowsHotKey

简介

Sage.WindowsHotKey 是一个功能强大的 Windows 全局热键管理库,提供了简单易用的 API 来注册、管理和响应全局热键。该库完全兼容 AOT 编译,适用于 .NET 应用程序。

主要特性

  • 支持全局热键注册和注销
  • 热键事件处理
  • 热键状态查询
  • 热键冲突检测
  • 热键显示管理
  • 完全兼容 AOT 编译

安装

通过 NuGet 安装

Install-Package Sage.WindowsHotKey

或者使用 .NET CLI:

dotnet add package Sage.WindowsHotKey

基本用法

注册和响应热键

using Sage.WindowsHotKey;
using Sage.WindowsHotKey.Models;
using System.Windows.Forms;

public partial class MainForm : Form
{
    private readonly HotKeyManager _hotKeyManager;

    public MainForm()
    {
        InitializeComponent();
        _hotKeyManager = new HotKeyManager(this);
        
        // 注册热键
        var result = _hotKeyManager.RegisterHotKey(
            "CaptureScreen",
            Keys.PrintScreen | Keys.Control,
            () => {
                Console.WriteLine("截图热键被按下");
                // 执行截图操作
            });
            
        if (result.Result == HotKeyRegisterResult.Success)
        {
            Console.WriteLine($"热键注册成功:{result.HotKeyId}");
        }
    }
    
    protected override void WndProc(ref Message m)
    {
        // 必须调用以处理热键消息
        if (_hotKeyManager.ProcessHotKey(m.Msg, m.WParam))
        {
            return;
        }
        
        base.WndProc(ref m);
    }
    
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _hotKeyManager.Dispose();
        }
        base.Dispose(disposing);
    }
}

使用事件处理热键

using Sage.WindowsHotKey;
using Sage.WindowsHotKey.Models;
using System.Windows.Forms;

public partial class MainForm : Form
{
    private readonly HotKeyManager _hotKeyManager;

    public MainForm()
    {
        InitializeComponent();
        _hotKeyManager = new HotKeyManager(this);
        
        // 订阅热键事件
        _hotKeyManager.HotKeyPressed += OnHotKeyPressed;
        
        // 注册热键
        _hotKeyManager.RegisterHotKey(
            "CaptureScreen",
            Keys.PrintScreen | Keys.Control,
            () => {});
            
        _hotKeyManager.RegisterHotKey(
            "OpenSettings",
            Keys.S | Keys.Alt,
            () => {});
    }
    
    private void OnHotKeyPressed(object sender, HotKeyEventArgs e)
    {
        switch (e.HotKey.Name)
        {
            case "CaptureScreen":
                Console.WriteLine("截图热键被按下");
                // 执行截图操作
                break;
                
            case "OpenSettings":
                Console.WriteLine("打开设置热键被按下");
                // 打开设置窗口
                break;
        }
    }
    
    protected override void WndProc(ref Message m)
    {
        // 必须调用以处理热键消息
        if (_hotKeyManager.ProcessHotKey(m.Msg, m.WParam))
        {
            return;
        }
        
        base.WndProc(ref m);
    }
}

使用 KeyDisplayManager 管理热键显示

using Sage.WindowsHotKey;
using Sage.WindowsHotKey.Models;
using System.Windows.Forms;

public partial class ShortcutSettingForm : Form
{
    private readonly HotKeyManager _hotKeyManager;
    private readonly KeyDisplayManager _keyDisplayManager;
    
    public ShortcutSettingForm(HotKeyManager hotKeyManager)
    {
        InitializeComponent();
        _hotKeyManager = hotKeyManager;
        
        // 创建热键显示管理器,设置等待按键时的提示文本
        _keyDisplayManager = new KeyDisplayManager(_hotKeyManager, "请按下组合键...");
        
        // 订阅快捷键注册事件
        _keyDisplayManager.ShortcutRegistered += OnShortcutRegistered;
        
        // 设置允许单键注册(通常不建议)
        _keyDisplayManager.AllowSingleKey = false;
        
        // 添加需要忽略的按键
        _keyDisplayManager.AddIgnoredKey(Keys.Escape);
    }
    
    private void OnShortcutRegistered(object sender, ShortcutRegisteredEventArgs e)
    {
        // 当用户完成快捷键设置时触发
        lblCurrentShortcut.Text = e.DisplayText;
        
        // 注册到热键管理器
        var result = _hotKeyManager.RegisterHotKey(
            e.HotKeyName,  // 热键名称
            e.KeyData,      // 按键组合
            () => { /* 热键触发时的操作 */ },
            true);         // 如果已存在则替换
            
        if (result.Result != HotKeyRegisterResult.Success)
        {
            MessageBox.Show("热键注册失败");
        }
    }
    
    private void txtShortcut_KeyDown(object sender, KeyEventArgs e)
    {
        // 处理按键事件并显示当前组合键
        string displayText = _keyDisplayManager.ProcessKeyDown(e, "MyHotKey");
        txtShortcut.Text = displayText;
    }
}

API 参考

HotKeyManager 类

热键管理器,用于管理全局热键的注册和处理。

构造函数
public HotKeyManager(IWin32Window window)
  • window: 拥有热键的窗口,窗体中必须处理了WndProc。
属性和事件
  • event EventHandler<HotKeyEventArgs> HotKeyRegistered: 热键注册成功时触发。
  • event EventHandler<HotKeyEventArgs> HotKeyUnregistered: 热键注销时触发。
方法
  • HotKeyRegisterInfo RegisterHotKey(string name, Keys keyData, Action callback, bool replaceIfExists = false): 注册新的热键。
  • bool UnregisterHotKey(string name): 注销指定名称的热键。
  • bool IsHotKeyNameExists(string name): 检查热键名称是否已存在。
  • IReadOnlyCollection<HotKeyData> GetRegisteredHotKeys(): 获取所有已注册的热键信息。
  • HotKeyData? GetHotKeyByName(string name): 获取指定名称的热键信息。
  • bool ProcessHotKey(int msg, nint wParam): 处理Windows消息。
  • bool IsHotKeyConflicting(Keys keyData, out HotKeyData? conflictingHotKey): 检查热键是否冲突。
  • void Dispose(): 释放资源,注销所有热键。

KeyDisplayManager 类

管理键盘快捷键的显示和注册。

构造函数
public KeyDisplayManager(HotKeyManager hotKeyManager, string? continueText = null)
  • hotKeyManager: 热键管理器,用于热键注册时的交互。
  • continueText: 按下等待显示的文本。
属性和事件
  • event EventHandler<ShortcutRegisteredEventArgs> ShortcutRegistered: 当有效的快捷键组合被注册时触发。
  • bool AllowSingleKey: 获取或设置是否允许注册单个按键(不包含修饰键的按键)。
  • string? ContinueText: 获取或设置等待按键时的提示文本,为null时只显示加号。
方法
  • string ProcessKeyDown(KeyEventArgs e, string hotKeyName): 处理按键按下事件,返回当前快捷键的显示文本。
  • void AddIgnoredKey(Keys key): 添加需要忽略的单个按键。
  • void RemoveIgnoredKey(Keys key): 移除忽略的单个按键。
  • void AddIgnoredKeyCombination(Keys keyCombination): 添加需要忽略的组合键。
  • void RemoveIgnoredKeyCombination(Keys keyCombination): 移除忽略的组合键。
  • void ClearIgnoredKeys(): 清除所有忽略的按键设置。

模型类

HotKeyData

表示单个热键的详细信息。

  • string Name: 热键的唯一名称。
  • Keys KeyData: 热键组合。
  • Action Callback: 热键触发时执行的回调。
  • int Id: 热键的唯一标识符。
HotKeyRegisterInfo

热键注册结果详情。

  • HotKeyRegisterResult Result: 注册结果。
  • string? ConflictingHotKeyName: 冲突的热键名称(如果有)。
  • int? ErrorCode: 系统错误代码(如果有)。
  • int? HotKeyId: 热键ID(注册成功时)。
HotKeyRegisterResult

热键注册结果枚举。

  • Success = 0: 注册成功。
  • Conflicting = -1: 热键已被占用。
  • Failed = -2: 注册失败(系统错误)。
  • InvalidArgument = -3: 参数无效。
HotKeyEventArgs

热键事件参数类。

  • HotKeyData HotKey: 热键数据。

注意事项

  1. 在使用 HotKeyManager 时,必须在窗体的 WndProc 方法中调用 ProcessHotKey 方法来处理热键消息。
  2. 在应用程序关闭时,应调用 HotKeyManager 的 Dispose 方法来释放资源,注销所有热键。
  3. 热键注册可能会失败,因为系统中可能已经有其他应用程序注册了相同的热键组合。
  4. 建议不要注册单个按键作为热键,因为这可能会干扰用户的正常输入。

许可证

本项目采用 Apache 2.0 许可证。详情请参阅 LICENSE 文件。

贡献

欢迎提交问题报告和改进建议。如果您想贡献代码,请提交拉取请求。

作者

  • LiuPengLai - 甲壳虫科技 欢迎提交问题和功能请求。 QQ Group: 1054304346
Product Compatible and additional computed target framework versions.
.NET net9.0-windows7.0 is compatible.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net9.0-windows7.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0.1 276 8/25/2025
1.0.0 121 7/16/2025