Search code examples
javaawtrobot

How to type Unicode character via Robot


How to type unicode character via robot in cross platform way ? I've seen solutions to this but only works on Windows eg: How to make the Java.awt.Robot type unicode characters? (Is it possible?), Is there a way to do this on Linux and Mac ?


Solution

  • If it's your goal to write something into an input field for example, this could probably work:

    // Set desired character
    String c = "ä";
    StringSelection selection = new StringSelection(c);
    // Copy it to clipboard
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(selection, null);
    // Paste it
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    

    Basically simulating a copy paste, but it will delete your current clipboard content, unless you save it. Under Mac OS you want to use VK_META instead of VK_CONTROL. Also, this will not work if you really have to simulate the keypress itself, only if you want to output it.