Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to create a very simple WPF application. I'd like to have an command handler called when the user presses "H" (not Control-H or Alt-H, just H). If I use the following in code-behind code:

var gesture = new KeyGesture(Key.H, ModifierKeys.None);
var inputBinding = new InputBinding(MyRoutedCommand, gesture);
InputBindings.Add(inputBinding);

I immediately get an exception saying that the key and modifier combination isn't supported for KeyGesture.

(I get the same exception if I create the XAML to do the analogous thing).

My application doesn't accept typed input, no text boxes are in the application, so there isn't really a conflict with text (at least in my mind). I wouldn't have thought that this would be so unusual.

I've seen comments elsewhere that suggest that I could create a custom control for this or intercept keyboard presses at a low level, but these seem like a lot of overhead. Any simpler thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

Don't use the KeyGesture type or property (as one key is not a gesture).

e.g.

KeyBinding b = new KeyBinding()
    {
        Command = MyRoutedCommand,
        Key = Key.H
    };
InputBindings.Add(b);

Same for XAML

<KeyBinding Command="{Binding MyRoutedCommand}" Key="H" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...