简体   繁体   中英

Simulate key type with Java Robot

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?

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.

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