Search code examples
wpfxamlkeygesture

Xaml LeftAlt in KeyGesture not allowed


How I can use this key combination in XAML?

<RoutedUICommand x:Key="GlobalExitCommand" Text="Execute GlobalExitCommand">
            <RoutedUICommand.InputGestures>
                <KeyGesture>LeftAlt+F1</KeyGesture>
            </RoutedUICommand.InputGestures>
        </RoutedUICommand>

The LeftAlt+F1 is not allowed. Thanks in advance


Solution

  • LeftAlt is not a valid ModifierKeys value. The valid values are None, Alt, Control, Shift and Windows.

    So you can't create a KeyGesture that only accepts the left ALT in XAML. You could use Alt and handle the rest in your Executed event handler though:

    <Window.Resources>
        <RoutedUICommand x:Key="GlobalExitCommand" Text="Execute GlobalExitCommand">
            <RoutedUICommand.InputGestures>
                <KeyGesture>Alt+F1</KeyGesture>
            </RoutedUICommand.InputGestures>
        </RoutedUICommand>
    </Window.Resources>
    <Window.CommandBindings>
        <CommandBinding Command="{StaticResource GlobalExitCommand}" Executed="CommandBinding_Executed" />
    </Window.CommandBindings>
    

    private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        if (Keyboard.IsKeyDown(Key.LeftAlt))
        {
            //...
        }
    }