Search code examples
javaawtrobot

How can I kill a rogue robot?


I am (ab)using Java's Robot class to automate some clicking tasks in a browser window. On the first click, the Java application loses focus. If the robot begins misbehaving, I would like to terminate the program. However, I cannot easily do so because the robot has control of my mouse.

What I would like to do is have my program listen for some kind of signal from me telling it to exit. For instance, the program could exit when the "escape" key is pressed. However, I do not know how to listen for keystrokes when the application is not in focus.

I am running Java SE 6 in OSX 10.9.

How might I be able to terminate my program under these circumstances?

Edit: After posting this, I found a related question addressing the same problem: Listening for input without focus in Java. (However, this is not an exact duplicate, as my question is a little broader.)


Solution

  • One option would be to check the mouse position before every call into Robot (or at regular intervals), to verify that it was still at whatever position it was last mouseMove'd to. If it detected a discrepancy, it'd throw an exception. That way, moving the mouse manually could be used to terminate things.

    Probably best to wrap Robot to ensure it always checks that. I suggest SecondLawObeyingRobot.