• Stars
    star
    311
  • Rank 134,521 (Top 3 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created almost 11 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A managed library to handle global hotkeys in Windows Forms and WPF applications

NHotkey

NuGet version NuGet version NuGet version AppVeyor build

Easily handle shortcut keys even when your WPF or WinForms app doesn't have focus. Declare hotkeys in XAML with the familiar KeyBinding syntax.

Nuget packages:

Windows Forms usage

Add a reference to NHotkey.dll and NHotkey.WindowsForms.dll. In the file where you want to handle hotkeys, import the NHotkey.WindowsForms namespace:

    using NHotkey.WindowsForms;

During initialization, add some hotkeys:

    HotkeyManager.Current.AddOrReplace("Increment", Keys.Control | Keys.Alt | Keys.Add, OnIncrement);
    HotkeyManager.Current.AddOrReplace("Decrement", Keys.Control | Keys.Alt | Keys.Subtract, OnDecrement);
  • the first parameter is an application-defined name for the hotkey; it can be anything you like, as long as it's unique;
  • the second parameter is the combination of keys for which you want to register a hotkey;
  • the last parameter is a delegate of type EventHandler<HotkeyEventArgs> that will be called when this hotkey is pressed. For instance:
    private void OnIncrement(object sender, HotkeyEventArgs e)
    {
        Value++;
        e.Handled = true;
    }

    private void OnDecrement(object sender, HotkeyEventArgs e)
    {
        Value--;
        e.Handled = true;
    }

If you want to handle several hotkeys with the same handler, you can check the Name property of the HotkeyEventArgs:

    private void OnIncrementOrDecrement(object sender, HotkeyEventArgs e)
    {
        switch (e.Name)
        {
            case "Increment":
                Value++;
                break;
            case "Decrement":
                Value--;
                break;
        }
        e.Handled = true;
    }

WPF usage

The approach for WPF is very similar to the one for Windows Forms; the exposed API is slightly different to account for the differences between WinForms and WPF. The WPF version also supports KeyBindings.

Add a reference to NHotkey.dll and NHotkey.Wpf.dll. In the file where you want to handle hotkeys, import the NHotkey.Wpf namespace:

    using NHotkey.Wpf;

During initialization, add some hotkeys:

    HotkeyManager.Current.AddOrReplace("Increment", Key.Add, ModifierKeys.Control | ModifierKeys.Alt, OnIncrement);
    HotkeyManager.Current.AddOrReplace("Decrement", Key.Subtract, ModifierKeys.Control | ModifierKeys.Alt, OnDecrement);
  • the first parameter is an application-defined name for the hotkey; it can be anything you like, as long as it's unique;
  • the second and third parameters are the key and modifiers for which you want to register a hotkey;
  • the last parameter is a delegate of type EventHandler<HotkeyEventArgs> that will be called when this hotkey is pressed.

To support applications that use the MVVM pattern, you can also specify hotkeys in XAML using InputBindings. Just declare KeyBindings as usual, and set the HotkeyManager.RegisterGlobalHotkey attached property to true:

    ...
    <Window.InputBindings>
        <KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}"
                    HotkeyManager.RegisterGlobalHotkey="True" />
        <KeyBinding Gesture="Ctrl+Alt+Subtract" Command="{Binding DecrementCommand}"
                    HotkeyManager.RegisterGlobalHotkey="True" />
    </Window.InputBindings>
    ...

Known limitations of this feature

  • the HotkeyManager can't detect if you remove a KeyBinding; it only relies on the attached property being set to true or false. If you want to remove a KeyBinding at runtime, make sure you set HotkeyManager.RegisterGlobalHotkey to false, otherwise it will still be registered
  • changing the keys or modifiers of a KeyBinding at runtime is currently not supported. If you need to modify a KeyBinding at runtime, you need to set HotkeyManager.RegisterGlobalHotkey to false, change the key, and set HotkeyManager.RegisterGlobalHotkey to true again.

More Repositories

1

WeakEvent

Generic weak event implementation
C#
182
star
2

Linq.Extras

A set of extension methods to complement the ones from System.Linq.Enumerable
C#
172
star
3

AspNetCore.AsyncInitialization

Async initialization in ASP.NET Core 2.x
C#
87
star
4

CosmosDBStudio

A tool to browse and query Azure Cosmos DB databases
C#
54
star
5

Extensions.Hosting.AsyncInitialization

Async initialization for .NET 6.0+ apps using the generic host (e.g. ASP.NET Core apps)
C#
45
star
6

NString

A collection of utilities for working with strings in .NET.
C#
37
star
7

GenerateCSharpErrors

Just a small program to generate the full list of C# errors and warnings
C#
35
star
8

Iso8601DurationHelper

Small library to handle ISO8601 durations in C#
C#
33
star
9

HumanBytes

A library to convert byte sizes to a human readable form
C#
32
star
10

AutoRunCustomTool

A Visual Studio extension that automatically runs the custom tool on a file when a trigger file is modified
C#
30
star
11

InternalsVisibleTo.MSBuild

Enables declaring 'InternalsVisibleTo' items in a .NET project file, rather than declaring them to an AssemblyInfo.cs file.
28
star
12

AspNetCore.SignalR.AzureServiceBus

Provides scale-out support for ASP.NET Core SignalR using an Azure Service Bus topic to dispatch messages to all server instances.
C#
15
star
13

AspNetCore.SystemTextJson.MultipleSettings

Use different JSON serialization settings in ASP.NET Core per controller or per action
C#
11
star
14

DontMergeMeYet

A GitHub app that adds an "in progress" status on a pull request to avoid merging it prematurely
C#
11
star
15

Hamlet

“To be, or not to be, that is the question”. A simple Option type for .NET
C#
10
star
16

EssentialMVVM

Minimalist MVVM framework
C#
7
star
17

Quack

[POC] Duck-typing framework for .NET
C#
6
star
18

blog

My personal blog, made with Hugo
HTML
5
star
19

TestDeviceFlow

Code for the blog article at
C#
5
star
20

FluentIL

A thin fluent wrapper for ILGenerator (Reflection.Emit)
C#
5
star
21

TestLinqPerf

Small benchmark to compare Linq performance in .NET Core vs. .NET 4.6.2
C#
4
star
22

TypeScriptCosmosDBStoredProceduresArticle

Code for the article "Using TypeScript to write Cosmos DB stored procedures with async/await"
TypeScript
4
star
23

CleanUpNetCoreSdk

A tool to remove outdated .NET Core SDKs
C#
3
star
24

OAuthUI

A portable class library that provides a UI for OAuth authentication on desktop and mobile platforms.
C#
2
star
25

ToastHelper

A strongly typed helper for toast notifications in Windows Store apps
C#
2
star
26

AyendeCsvIndexQuestion

My attempt at solving Ayende's interview question on how to implement an index to quickly search a large CSV file
C#
2
star
27

GitLog

A simple tool to show the commit history of a Git repository, including changes in submodules
C#
2
star
28

Extensions.Caching.Extras

Adds features to Microsoft.Extensions.Caching such as partitioning and eviction
C#
2
star
29

thomaslevesque

2
star
30

NSettings

Extensible application settings framework with minimal boilerplate code
C#
2
star
31

Solo

Simple library to run app as single-instance and notify the existing instance, if any.
C#
2
star
32

BrowserSelector

[WORK IN PROGRESS] Simple tool to control in which browser a URL is opened, instead of always using the system default browser
C#
2
star
33

blog-code-samples

Sample code for my blog
C#
1
star
34

SharpADS

A library that provides access to NTFS alternate data streams
C#
1
star
35

GitBrowse

A command line tool to open the webpage for a GitHub repo
C#
1
star
36

GemBox

This repository contains various bits of code that don't fit anywhere else. Don't expect consistency here, there isn't any ;)
C#
1
star
37

TarSharp

A .NET library to read and write TAR archives
C#
1
star
38

blog-fr

L'archive de mon blog personnel en français, réalisée avec Hugo https://thomaslevesque.fr
HTML
1
star
39

Unity.Extras.AutoFactory

A Unity extension to automatically generate strongly typed factories at runtime.
C#
1
star
40

TestDeploy

Dummy repo to test automated deployment
C#
1
star
41

dotnet-project-templates

Project templates for my personal use. Probably only useful to me, but feel free to use if you want.
C#
1
star