为robot.keyPress(java.awt.event.KeyEvent.VK_something)动态生成VK_something

时间:2018-07-24 16:40:57

标签: java

我可以使用KeyEvent做类似KeyCode.valueOf(“ G”)的事情吗? 我想按键盘上的键,我不想对所有这样的字母和组合写相同的代码

            robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
            robot.keyPress(java.awt.event.KeyEvent.VK_G);
            robot.keyRelease(java.awt.event.KeyEvent.VK_G);
            robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);


            robot.keyPress(java.awt.event.KeyEvent.VK_M);
            robot.keyPress(java.awt.event.KeyEvent.VK_0);
            robot.keyRelease(java.awt.event.KeyEvent.VK_0);
            robot.keyRelease(java.awt.event.KeyEvent.VK_M);

我想做类似的事情:

 def press(arg1, arg2):
            robot.keyPress(java.awt.event.KeyEvent.VK_arg1);
            robot.keyPress(java.awt.event.KeyEvent.VK_arg2);
            robot.keyRelease(java.awt.event.KeyEvent.VK_arg2);
            robot.keyRelease(java.awt.event.KeyEvent.VK_arg1);

1 个答案:

答案 0 :(得分:0)

    Robot robot = new Robot();
    String sampleString = fooBar;
    int arg1 = sampleString.charAt(0);
    int arg2 = sampleString.charAt(1);

    robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(arg1));
    robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(arg1));
    robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(arg2));
    robot.keyRelease(KeyEvent.getExtendedKeyCodeForChar(arg2));