Search code examples
loopskeypress

How to get r.keypress to run a loop?


I have a simple script written with r.keypress:

import java.awt.AWTException;
import java.awt.Robot;
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();
    r.keyPress(KeyEvent.VK_H);
    r.keyPress(KeyEvent.VK_A);
    r.keyPress(KeyEvent.VK_P);
    r.keyPress(KeyEvent.VK_P);
    r.keyPress(KeyEvent.VK_Y);
    r.keyPress(KeyEvent.VK_SPACE);
    r.keyPress(KeyEvent.VK_B);
    r.keyPress(KeyEvent.VK_I);
    r.keyPress(KeyEvent.VK_R);
    r.keyPress(KeyEvent.VK_T);
    r.keyPress(KeyEvent.VK_H);
    r.keyPress(KeyEvent.VK_D);
    r.keyPress(KeyEvent.VK_A);
    r.keyPress(KeyEvent.VK_Y);
}
}

The issues are twofold. Firstly, it won't output double characters, and keyrelease just throws unhandled exceptions. I don't know why it wouldn't work, but KeyRelease works now as
r.keyRelease(KeyEvent.VK_SPACE); Secondly, I want to use this to output a series of numbers, i.e, 1, 2, 3, etc all the way to 1000000. Is this possible with keypress, and if not, what's the alternative to still use it wherever my cursor is?


Solution

  • I actually solved this one on my own 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);
        } 
    
    }
    
    
    
    
    }