3

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.

Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
  • 1
    Instead of thousand words http://stackoverflow.com/questions/397113/how-to-make-the-java-awt-robot-type-unicode-characters-is-it-possible – mishadoff Mar 22 '12 at 00:30
  • Tried all the answers on that post an none solved my problem... But appreciated the comment. Thanks – Ismael Abreu Mar 22 '12 at 01:41

1 Answers1

4

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);
    }
}
ɲeuroburɳ
  • 6,990
  • 3
  • 24
  • 22
  • Nice, that worked. But I'm not sure if it solves my problem. I think I have to send the keypress for each char to solve my problem. – Ismael Abreu Mar 22 '12 at 03:23
  • and I needed to change to VK_META instead of VK_CONTROL to work on mac. You can add that to your answer – Ismael Abreu Mar 22 '12 at 03:25
  • Updated. I haven't tested on my Mac yet, but it should be closer now. If you need a key-press event per character, you might be able to get away with updating the clipboard contents with a new character for each ⌘-V you hit. – ɲeuroburɳ Mar 22 '12 at 04:30
  • I couldn't make it on Mac. I really needed each key press, and there was a problem with the shift key that wasn't working. I just work arround doing it on a windows pc. I will just accept your answer because it would be a good way to solve it if I just needed the text entered instead of each key press. Thanks – Ismael Abreu Mar 29 '12 at 00:03