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!

Jlee523
  • 147
  • 4
  • I saw this post https://stackoverflow.com/questions/10924246/java-robot-class-add-focus-to-a-specific-running-application recently and maybe am just missunderstanding it? Additionally, I am on a Mac if that means anything – Jlee523 Aug 08 '18 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 – MadProgrammer Aug 08 '18 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. – Joel Aug 08 '18 at 22:16

1 Answers1

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

Micromuncher
  • 903
  • 7
  • 19