简体   繁体   中英

How to make Java Robot hold down a key?

I want to hold down a key for a certain amount of time using the Java robot. I have read other similar threads, but none of them work. Repeatedly pressing the key will only result in the key not releasing.

Here's my code so far (It does not work since it only presses the key once):

new Thread(new Runnable() {
         public void run() {
             final int keyP = 0; //the key to press

                            final int duration = 2000 //2 seconds
                            Robot r = null;
                            try {
                                r = new Robot();
                            } catch (AWTException e1) {
                                                        e1.printStackTrace();
                            }
                            r.keyPress(keyP);
                            r.delay(duration); //Thread.sleep does the same thing
                            r.keyRelease(keyP);

                            }
                 }).start();

Try:

boolean keepPressing=true;
long startTime = System.currentTimeMillis();
long endTime=null;
long totalTime=null;

while(keepPressing){
    r.keyPress(keyP);
    endTime=System.currentTimeMillis();
    totalTime = endTime - startTime;
    if(totalTime>1999) {
      keepPressing=false;
      r.keyRelease(keyP);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM