user4608242
user4608242

Reputation:

C# WinForms Key Bindings

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

Answers (1)

Peter Duniho
Peter Duniho

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:

  1. Shortcut keys, i.e. 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.
  2. Various key event handling in the UI. This can get fairly complicated depending on your needs, but is often the most appropriate way, and is the primary way to handle key input not associated with a menu item. The simplest event is the 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

Related Questions