2018-03-12

[JAVA] How to type " underline _ " character using java.awt.Robot

java.awt.Robot is a very powerful library to control and simulate human's keyboard type and mouse click actions. But some special characters like "_" (the library contanst is KeyEvent.VK_UNDERSCORE) will invoke an error as follow.

       
Exception in thread "main" java.lang.IllegalArgumentException: Invalid key code
 at sun.awt.windows.WRobotPeer.keyPress(Native Method)
 at java.awt.Robot.keyPress(Robot.java:243)


The solution is:
       
public void underline() {
    keyPress(KeyEvent.VK_SHIFT);
    keyPress(KeyEvent.VK_MINUS);
    keyRelease(KeyEvent.VK_MINUS);
    keyRelease(KeyEvent.VK_SHIFT);
}

public void keyClick(int k) {
    keyPress(k);
    delay(50);
    keyRelease(k);
}


Cheers.