javaawtrobot

How to use Java Robot to enter an increasing sequence of numbers using robot.keypress?


I am trying to use Java to write a very simple script: I want to place my cursor in a debug console and have it type a sequence of numbers. For example

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, etc. But I also need it to press enter, then the up arrow, then type, then enter, then up arrow, etc. So 1 Enter Up Arrow 2 Enter Up Arrow etc.

Alternatively, it can also just use the enter key, as in "age -100 (1-100000).

Here is the code I'm trying to make work, but I don't know how to make it count.

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
public class robot {

public static void main(String[] args) throws AWTException, InterruptedException{
    // TODO Auto-generated method stub
    Robot r = new Robot();
    String i = "";
    Thread.sleep(2000);
    String text = "1";
    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);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    

}


}

Solution

  • I actually solved this one after several days of mashing code. It is, however, very, very messy and slips about once every 300 lines. Also, if you drop ThreadSleeps below 10 ms it crashes about 200 lines in. It needs both ThreadSleeps or it crashes almost immediately.

    import java.awt.AWTException;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import java.awt.event.KeyEvent;
    import java.util.concurrent.TimeUnit;
    public class robot {
    static int i;
    public static void main(String[] args) throws AWTException, InterruptedException{
        // TODO Auto-generated method stub
    for (int i=39000; i< 40000; i+=1) {
    
        String str = "age -100 " + i;
        Robot r = new Robot();
        Thread.sleep(10);
        String text = str;
        StringSelection stringSelection = new StringSelection(text);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, stringSelection);
        Thread.sleep(10);
        Robot robot = new Robot();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        } 
    
    }
    
    
    
    
    }