简体   繁体   English

如何使Java Robot按住一个键?

[英]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. 我想使用Java机器人按住某个键一段时间。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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