I am trying to control an application running in Windows 7 by sending keystroke shortcuts to that application.
The following code illustrates my problem using Microsoft Word. It launches the word application and successfully writes the "x" into the document. However, when I click on the Java JButton nothing happens. How can I fix this?
Thanks very much for any suggestions.
I'm not sure if that helps, but to simulate a physical keypress, you need to call robot.keyRelease(//same key code); after calling keyPress. Otherwise the first key pressed is still down and might be conflicting with other keyPress events.
Thanks for the suggestion. Unfortunately, it didn't solve my problem but while experimenting with the program I discovered what is going on:
until I click the JButton, the Word application is the active window and keyboard output goes there. When I click the JButton the Java GUI becomes the active window and keyboard output no longer goes to the Word application. If I put a long delay in the JButton action-performed before sending the key strokes and use that time to manually activate the Word application (by clicking on it) subsequent keystrokes are entered into Word.
The question becomes then, how do I pass the focus back onto the Word application programmatically from Java?
(I have looked at many Java Robot exampleson the Internet but none of them have a Java GUI. Perhaps the Robot class is not designed to do this?)
Here is my revised program:
The link shows a very simplistic example (no pointer location). There is a Robot.mouseMove method, as well. Unfortunately, you will be opening that can-of-worms: knowing what parts of the screen belong to what. Maybe you can compute something based on the location of the input field you are using?
Works great! (Found lots of other tutorials with more extensive use of the robot mouse). Now, if I can program/initialize my application to appear in the same screen location every time, I can set up my Java GUI to share my screen nicely with the application and I'm home free.
In the meantime, I still haven't given up figuring out a way to transfer focus to the application without using robot mouse clicks. This would be "cleaner" as it would not depend on knowing the location of the application on the screen. But if I can't do that, the above solution should work very well.
I just tried that and it works fine. There is a slight aesthetics problem in that the screen very briefly flashes what looks like an array of large icons (it happens so fast that I I'm not able to see what it is) before transferring focus to the previous window. It's always good to have more than one way to do something in case I run into problems using the absolute screen location mouse click. Thanks for the suggestion.