Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accent with robot keypress

Tags:

java

awtrobot

I've been trying to use Robot from awt, to input some text on a app. The problem it's that i can't make it type any letters like ê, à or á. I have tried doing this such printing ^e for example but even that works, it just dosen't print anything for VK_CIRCUMFLEX

Not sure if it matters but i'm testing on a Mac.

Any help would be well come.

like image 852
Ismael Avatar asked Nov 19 '25 10:11

Ismael


1 Answers

You can use the clipboard combined with CTRL/COMMAND+V to do the job for you. The code below works on Windows at least (Mac key combo probably requires a different sequence to do a paste).

public static void main(String[] args) throws AWTException {
    String osName = System.getProperty("os.name");        
    boolean isOSX = osName.startsWith("Mac OS X");
    boolean isWin = osName.startsWith("Windows");

    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection str = new StringSelection("Héllõ Wörld");
    clipboard.setContents(str, str);
    Robot robot = new Robot();

    if (isMac) {
        // ⌘-V on Mac
        robot.keyPress(KeyEvent.VK_META);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_META);        
    } else if (isWin) {
        // Ctrl-V on Win
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    } else {
        throw new AssertionError("Not tested on "+osName);
    }
}
like image 130
ɲeuroburɳ Avatar answered Nov 21 '25 22:11

ɲeuroburɳ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!