Java机器人类型大写,小写和字符串符号

时间:2018-03-01 13:17:05

标签: java

我如何制作此类型的大写字符?和符号?例如,要使机器人键入字符串" TeSt!// 123 $"或其他类似的东西?

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);
    }
}

我尝试更改代码,但仍然没有运气。

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

1 个答案:

答案 0 :(得分:0)

Haven未经过测试,但我认为你需要像

这样的东西
    if (needsShift(c)) {
        robot.keyPress(KeyEvent.VK_SHIFT);
        robot.delay(100);
    } 
    robot.keyPress(keyCode);
    robot.delay(100);
    robot.keyRelease(keyCode);
    robot.delay(100);
    }
    if (needsShift(c)) {
        robot.keyRelease(KeyEvent.VK_SHIFT);
        robot.delay(100);
    } 

您可以只为大写

启动方法
private boolean needsShift(Character c) {
    return Character.isUpperCase(c);
}

然后你需要扩展它以包含一个字符映射到需要shift键到达的键码。注意:密钥代码与特定的键盘布局相关联。