简体   繁体   English

如何使机器人按住鼠标按钮一段时间?

[英]How can I make Robot press and hold a mouse button for a certain period of time?

I am using Java to generate a mouse press using the Robot class: 我正在使用Java来使用Robot类生成鼠标按下:

robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);

However, I want the Robot to press the button for a certain period of time. 但是,我希望机器人按下按钮一段时间。 How can I achieve this? 我怎样才能做到这一点?

Just sleep a bit between the two actions (specified in milliseconds): 只需在两个动作之间稍微睡一会儿(以毫秒为单位):

  1. Thread.sleep(long millis);

     robot.mousePress(InputEvent.BUTTON1_MASK); try { Thread.sleep(1000); } catch(Exception e) {} // Click one second robot.mouseRelease(InputEvent.BUTTON1_MASK); 
  2. Robot.delay(long millis);

     robot.mousePress(InputEvent.BUTTON1_MASK); robot.delay(1000); // Click one second robot.mouseRelease(InputEvent.BUTTON1_MASK); 

I did that, it's simple: when you detect the mouse is pressed, you save the System.currentTimeMillis() . 我做到了,很简单:当您检测到鼠标被按下时,您保存System.currentTimeMillis() When you detect the mouse is released, you just check how long it was pressed. 当您检测到鼠标被释放时,您只需检查它被按下的时间。

If you want the action to be made after a certain amount of time, even if the mouse is still pressed, you start a thread that lives the desired amount of time when pressed and you interrupt it when releasing. 如果您希望在一定时间后执行操作,即使仍然按下鼠标,也会启动一个按下所需时间的线程,并在释放时中断它。 If the thread isn't interrupted in the amount of time you wanted, the action will be performed. 如果线程没有在您想要的时间内中断,则将执行操作。

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

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