2

I write a method to simulate key press from KeyEvent, like below:

private Robot robot(){
        if(robot==null){
            try {
                return new Robot();
            } catch (AWTException e) {
                throw new RuntimeException("Failed to create instance of Robot");
            }
        }else{
            return robot;
        }
    }

public void sendKeyEvent(KeyEvent evt) throws IOException {
        int type = evt.getID();
        if(type == KeyEvent.KEY_PRESSED){
            if(evt.isShiftDown()){
                robot().keyPress(KeyEvent.VK_SHIFT);
            }
            robot().keyPress(evt.getKeyChar());
        }else if(type == KeyEvent.KEY_RELEASED){
            robot().keyRelease(evt.getKeyChar());
            if(evt.isShiftDown()){
                robot().keyRelease(KeyEvent.VK_SHIFT);
            }
        }
    }

When this method received press 'A' key event, it could type 'A'.

java.awt.event.KeyEvent[KEY_PRESSED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='A',modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_UNKNOWN]]

But the problem is when it received this KeyEvent(press 'a'), it acturaly pressed "1".

java.awt.event.KeyEvent[KEY_PRESSED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='a',keyLocation=KEY_LOCATION_UNKNOWN]]

Could anyone tell me what wrong with this method?

1
  • For better help sooner, post an SSCCE. Commented Dec 17, 2011 at 16:23

1 Answer 1

4

It's a bit tricky and confusing and you got confused.

There are no 'uppercase a' and 'lowercase a' key events. There are just 'A/a' events and you can have or not a SHIFT modifier.

It just happen to be that VK_A to VK_Z are identical to ASCII 'A' through 'Z' but not so for 'a' to 'z'.

When you're re-sending the 'a' (ASCII 0x61, aka 97) that you got from getKeyChar(), you're actually sending VK_NUMPAD1, which is why you get the '1'.

The JavaDoc for getKeyChar says this:

getKeyChar() Returns the character associated with the key in this event. For example, the KEY_TYPED event for shift + "a" returns the value for "A"

So when you try with 'A', you get back VK_A and things work as you expect. But when you simply type 'a', you get 0x61 which is not what you want.

As far as I can tell changing getKeyChar() to getKeyCode() would fix your problem.

That said I wouldn't go messing with KEY_PRESS/KEY_RELEASED. I'd simply intercept KEY_TYPED and "Robot" from there.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.