使用java.awt.Robot键入字符串

2022-09-01 10:15:18

我已经知道如何使用 键入单个字符,如下所示。如何一次在文本框中输入整个预定义的值?java.awt.RobotkeyPressString

robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);  
// instead, enter String x = "111"

答案 1

常见的解决方案是使用剪贴板:

String text = "Hello World";
StringSelection stringSelection = new StringSelection(text);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);

答案 2

从Java 7开始,你也可以使用KeyEvent.getExtendedKeyCodeForChar(c)。仅小写的示例可以是:

void sendKeys(Robot robot, String keys) {
    for (char c : keys.toCharArray()) {
        int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
        if (KeyEvent.CHAR_UNDEFINED == keyCode) {
            throw new RuntimeException(
                "Key code not found for character '" + c + "'");
        }
        robot.keyPress(keyCode);
        robot.delay(100);
        robot.keyRelease(keyCode);
        robot.delay(100);
    }
}

推荐