0

I've been reading up on this and haven't found an answer that has made sense to me.

I'm trying to write a program in Java to interact with an application to see if I can write a program to play a video game for me. The game is on my computer.

Here is an excerpt of code:

public static void main(String[] args) throws java.io.IOException {

    Runtime run = Runtime.getRuntime();

    run.exec("open /Applications/OpenEmu.app");

    try {

        Robot robot = new Robot();


        System.out.println("Waiting 5 Seconds");
        //robot.delay(5000);

        System.out.println("Pressed X");
        robot.keyPress(KeyEvent.VK_X);
        robot.keyPress(KeyEvent.VK_X);
        robot.keyPress(KeyEvent.VK_X);
        robot.keyPress(KeyEvent.VK_X);
        //Starts an easy mode game

It opens the application fine, and in something like notepad, it will type XXXX, but it won't do so for the game?

I've assigned the 'x' key on my keyboard as a command button for the game. My guess is that the 'x' press is internal. All help is appreciated!

3
  • I saw this post stackoverflow.com/questions/10924246/… recently and maybe am just missunderstanding it? Additionally, I am on a Mac if that means anything Commented Aug 8, 2018 at 21:33
  • Aside from micormuncher's answer, a window can only respond to key events if it has keyboard focus, something to keep in mind Commented Aug 8, 2018 at 22:11
  • Just a theory, but it is possible that some games aren't using the system default input interface. For instance if I remember correctly, games in Windows using DirectX won't use the windows API for keyboard input, but something different (DirectInput). I don't know for mac, it might be the same problem here. Commented Aug 8, 2018 at 22:16

1 Answer 1

2

If you are trying to simulate input, try add robot.keyRelease as well. Javadoc for robot says for keyPress "Presses a given key. The key should be released using the keyRelease method."

    System.out.println("Pressed X");
    robot.keyPress(KeyEvent.VK_X);
    robot.keyRelease(KeyEvent.VK_X);
    ...

Also remember this: https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html "Note that some platforms require special privileges or extensions to access low-level input control. "

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.