5
votes

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

1
"Automate some clicking tasks in a browser window" Did you try to use Selenium ?NiziL
I don't think you can do it... I would mean to listen to the keyboard for a particular key combination, and this is impossible with plain java. You could use JNI/JNA and code your native layer for handling this key combinationBackSlash
@Nizil A browser is just an example; the robot might be interacting with any application. The question I am interested in is how to interrupt whatever the robot is doing.augurar
@augurar Well, if you robot must be able to interact with any application, Selenium is not a good idea :P Good luck with this :)NiziL

1 Answers

7
votes

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.