简体   繁体   中英

How to register a user-defined hotkey?

I'm building an app for the Windows Desktop with VS Express 2010. I'm kind of a newbie when it comes to C# and .Net, but I feel like I've managed to come pretty far. However, now I've gotten stuck on a small issue that I need help or advice with.

What I've done so far is that I've made a form with an input where the user can define a hotkey. I save this information like this:

private void newSessionHotkey_KeyDown(object sender, KeyEventArgs e)
{
    Properties.Settings.Default.HotkeyNewSession = converter.ConvertToString(e.KeyData);
    Properties.Settings.Default.Save();
}

But now that I've managed to save the hotkey, I notice that the RegisterHotKey API expects the hotkey to be seperated into two variables: one with modifiers and one with the key. But from what I understand I only have a Keys-object right now.

Does anyone have any suggestions for how I can turn my saved value into something that RegisterHotKey accepts?

This depends on whether you're making a WPF or WinForms application, but the WPF way is to make a "Command" and then adding the shortcut combination to the Command you created as an InputGesture.

In your codebehind:

public static RoutedCommand SaveCommand = new RoutedCommand();
SaveCommand.InputeGestures.Add(new KeyGesture(Key.S, ModifierKeys.Control));

Seperately:

private void SaveCommandExecuted(object sender, ExecutedRoutedEventArgs e ) 
{ /* Code to execute here */ }

In your XAML:

<Window.CommandBindings>
<CommandBinding Command="{x:Static local:MyWindow.SaveCommand}" Executed="SaveCommandExecuted"/>
</Window.CommandBindings>

Basically what this does is it creates a watcher that looks for keyboard events on the window, when it finds one that matches your key combination (and gesture attached to your Command objects), it then runs the function it has listed in the "Executed" argument of the XAML CommandBinding (as in: function to execute when the command is executed).

Let me know if you're using WinForms and I'll edit to include that method as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM