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

夙愿已清 提交于 2019-12-01 04:13:01

问题


I am using Java to generate a mouse press using the Robot class:

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?


回答1:


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);
    



回答2:


I did that, it's simple: when you detect the mouse is pressed, you save the 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.



来源:https://stackoverflow.com/questions/6401467/how-can-i-make-robot-press-and-hold-a-mouse-button-for-a-certain-period-of-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!