Reputation:
What is the closest equivalent of Java's KeyBindings in C#? I am attempting to port a Swing application to C#, but it is unclear which method I should use.
Here is a sample of the Java I am porting:
Action goUp = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
panel.upPressed = true;
}
};
Action stopUp = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
panel.upPressed = false;
}
};
InputMap getInputMap = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
getInputMap.put(KeyStroke.getKeyStroke("W"), "goUp");
getInputMap.put(KeyStroke.getKeyStroke("released W"), "stopUp");
panel.getActionMap().put("goUp", goUp);
panel.getActionMap().put("stopUp", stopUp);
Upvotes: 0
Views: 1297
Reputation: 70652
In Winforms, I am not aware of anything that is exactly like InputMap
. Keyboard input is usually handled in one of two ways:
MenuItem.Shortcut
. This is assignable in the Designer, or in code. Pressing the associated key will invoke the menu item's Click
event handler(s). Of course, to use this method requires that the action you want to take is represented in the UI as a menu item.KeyPress
event. Given your example, you probably want to handle KeyDown
and KeyUp
so that you can track the actual state of the key. Note that you will receive multiple KeyDown
events as the auto-repeat kicks in for a key; if this would be a problem for your handler, you'll need to track the key state and for a key for which you've already seen KeyDown
, only handle the KeyDown
event if you've seen the corresponding KeyUp
event.Note that WPF does have a key binding model that is more similar to InputMap
. Of course, the syntax is entirely different, but it breaks apart the idea of the menu items, commands, and key bindings, so you can mix and match as necessary (and in particular, have key bindings that don't correspond to any menu item). So if using WPF is an option, you might find that part of the transition easier (and probably only that part, since Swing is otherwise much more like Winforms than WPF :) ).
Upvotes: 1