简体   繁体   中英

How can I prevent the CTRL KeyEvent from being dispatched when pressing the right ALT key (ALT Gr)?

I am writing a key binding system for my application using key events from Swing. I am detecting the key presses using a KeyListener which I added to my Canvas.

Canvas canvas = new Canvas()
frame.add(canvas);
canvas.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("KEY CODE: " + e.getKeyCode() + " KEY LOCATION: " + e.getKeyLocation());
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
});

Everything works as indented, the keyPressed(KeyEvent e) method of the KeyListener gets called for every key pressed on the keyboard.

The Problem arises when I press the aforementioned right ALT key. It results in two consecutive KeyEvents being dispatched. One for the left CTRL key, and one for the right ALT key. As far as I know the so dispatched event for the CTRL key is indistinguishable from the KeyEvent which is dispatched when actually pressing the CTRL key.

Is there a way to prevent the CTRL event from being dispatched when pressing the right ALT key, or do I have to make the right ALT key unbindable in order to avoid confusing behaviour?

Based on an answer in:

When i press the right alt key on my keyboard the left control gets registered pressed?

Some keyboards have al ALT key on the left, and an ALT GR key on the right, if you have an ALT GR key, then it is correct that pressing that key will trigger an even that tells the operating system that Alt +Ctrl was pressed, this is normal.

It should mentioned that in some Windows keyboard layouts you have not this problem and right ALT key acts as ALT only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM