Question

Comment détecter une touche de raccourci telle que Ctrl + O dans un WPF (indépendamment de tout contrôle particulier)?

J'ai essayé de capturer KeyDown mais le KeyEventArgs ne me dit pas si Control ou Alt est ou non vers le bas.

Était-ce utile?

La solution

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
    {
        // CTRL is down.
    }
}

Autres conseils

J'ai enfin compris comment faire cela avec les commandes en XAML. Malheureusement, si vous souhaitez utiliser un nom de commande personnalisé (pas une des commandes prédéfinies telles que ApplicationCommands.Open), il est nécessaire de le définir dans le codeBear, quelque chose comme ceci:

namespace MyNamespace {
    public static class CustomCommands
    {
        public static RoutedCommand MyCommand = 
            new RoutedCommand("MyCommand", typeof(CustomCommands));
    }
}

Le XAML ressemble à ça ...

<Window x:Class="MyNamespace.DemoWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyNamespace"
    Title="..." Height="299" Width="454">
    <Window.InputBindings>
        <KeyBinding Gesture="Control+O" Command="local:CustomCommands.MyCommand"/>
    </Window.InputBindings>
    <Window.CommandBindings>
        <CommandBinding Command="local:CustomCommands.MyCommand" Executed="MyCommand_Executed"/>
    </Window.CommandBindings>
</Window>

Et bien sûr, vous avez besoin d’un gestionnaire:

private void MyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
    // Handle the command. Optionally set e.Handled
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top