0

我正在开发一个程序,它以类似人类的方式在 Java 中模拟按键。目标是每 x 秒发送一次随机按键(x 是两个整数之间的随机数)。这是我到目前为止的代码:

public class AutoKeyboard {

    public static int randInt(int min, int max) { // Method to generate random int
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }

    public static void main(String[] args) throws InterruptedException {

        int running = 1;

        while (running == 1) {
            try {

                int delay = randInt(336415,783410); // Generates random int between two integers
                Robot robot = new Robot();

                Thread.sleep(delay); // Thread sleeps for x (random int) milliseconds
                robot.keyPress(KeyEvent.VK_SPACE); // Simulating press of space bar

            } catch (AWTException e) {
                e.printStackTrace();
            }
        }
    }
}

我想要实现的是 Keyevent.VK_SPACE 是随机的,因此它可以是列表中的任何键(例如它会按 AD 中的随机键),而不是空格键。我该怎么做呢?我想不出具有我已经拥有的编程知识的合乎逻辑的解决方案(可悲的是很少)

感谢您的任何回复。

4

3 回答 3

1

您可以定义一个数组(如果您愿意,也可以是一个列表)(final static会很好),其中包含您希望能够按下的所有可能的键。这可能相当冗长,但让您可以灵活地使用所需的任何键:

int possibleKeys = new int[]{
    KeyEvent.VK_SPACE, 
    KeyEvent.VK_0,
    KeyEvent.VK_A,
    KeyEvent.VK_UP
};

对于共享相同 ASCII 值的常量,您甚至可以使用相应的字符:

int possibleKeys = new int[]{
    ' ',
    '0',
    'A', // careful not to use 'a' though!
    KeyEvent.VK_UP
};

然后从该数组中选择一个随机键码:

Random rand = new Random();
int i = rand.nextInt(possibleKeys.length);
int keyCode = possibleKeys[i];

另外,我看到您缺少robot.keyRelease应该在以下操作之后完成的操作robot.keyPress

robot.keyPress(keyCode);   // Simulating press of a key
robot.keyRelease(keyCode); // Simulating release of a key
于 2013-11-19T01:14:59.273 回答
0

由于 KeyEvent 为键定义了纯整数,因此您可以使用它们来代替 KeyEvent.VK_X。那么得到一些随机整数应该不是问题。
请访问http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/event/KeyEvent.html获取键码。

于 2013-10-11T19:30:58.157 回答
0

我只会生成一个介于 33 和 126 之间的随机数。然后每两个 char 随机添加一个 32。32 是一个空格。65-90 为大写,97-122 为小写。

好资源:http ://www.asciitable.com/

要生成一个随机数,我会:

Random randomGenerator = new Random();
int ran = randomGenerator.nextInt(126 - 33);
ran += 33;

然后跑将是你的随机角色。你可以有一个循环并做几次。

您甚至不需要使用 KeyEvent.VK_SPACE。如果您使用:

System.out.println(KeyEvent.VK_SPACE);

您将得到“32”的回报。这对应于 ASCII 图表,只需使用它。

于 2013-10-11T19:31:01.547 回答