简体   繁体   中英

C# Hotkeys while holding Control

I am trying to add some hotkeys to my Window application so that if i press Ctrl+Q it will perform an action. I can't quite figure this out. I looked through stack overflow and MSDN but i can't find the answer i need. So this is what i currently have

xaml:

<Grid KeyDown="Grid_KeyDown" KeyUp="Grid_KeyUp">
    <Menu Height="20" VerticalAlignment="Top" >
        <MenuItem Name="MenuItemFile"  Header="File" >
            <MenuItem Name="CloseApp" Header="Close" Icon="" Click="CloseApp_Click" AutomationProperties.AcceleratorKey="Control L" InputGestureText="Ctrl+X"/>
        </MenuItem>

c#

private void Grid_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.LeftCtrl)
        {
            switch (e.Key)
            {
               case Key.L:
                  This.Close();
                  break;
            }
        }
    }

You can simply do that by

private void Grid_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Q && e.Modifiers == Keys.Control)
    {
        // do stuff
    }
}

This is in a different direction now, but WPF has Commands which can help you with this as well. You can define a RoutedCommand or RoutedUICommand and append EventHandlers to the CanExecute and Executed events. Commands can also have KeyBindings in combination with modification keys like Ctrl or Shift . This is particularly useful when you want to structure a bigger application.

Here are some details on How to: Create a RoutedCommand and an overview about commands

You can bind a key to a command in your XAML:

<Window.InputBindings>
    <KeyBinding Key="Q" Modifiers="Control" Command="ApplicationCommands.Close"/>
</Window.InputBindings>

<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Close" Executed="CloseCommandHandler"/>
</Window.CommandBindings>

Then define what the command should do in your code-behind:

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

Or map it to a command in your ViewModel, if you're using the MVVM pattern.

Can you use ALT instead of CTRL? Is so, give this a try - it is built right in:

Mnemonic Keys in WPF

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