Macro, Capture MOUSE and KEYBOARD

Asked

Viewed 1,393 times

1

I need to do a macro, capturing mouse and keyboard. How should I proceed in JAVA? I need some specific API ?

  • Does it really have to be in Java? Java is a high-level language, and its purpose is far from dealing with communication with hardware, it will definitely need some library specific to the OS in question. If you are using Windows and want control mouse and keyboard can use Autoit, however I believe that it will not succeed capture.

  • What do you mean by macro? do you want to know all mouse movements over a period of time?

2 answers

3


If I understood correctly, the idea of making a Macro would be to automate a task, as if it were a user using the computer.

The Java API provides the class Robot to do so. It contains methods that trigger simple events such as mouseMove, mousePress and keyPress.

For automation of simple tasks it should work well. However, the documentation warns that in some systems special permissions may be required to function.

I don’t know this API very well, so I can’t tell you what are the limitations and problems that can occur.

If you need something more elaborate you can try a third-party API, such as the jNativeHook, which provides a Java API interface with native methods of the Operating System API. In fact, the idea is the same as in the class Robot, but they promise more functionality.

  • Thank you very much.

3

Just to complete the @utluiz reply

Some practical examples of the use of these functions:

Uncontrolled mouse randomly walks by the screen:

public static  void movemouse(){
        Robot robot = null;
        try {
            robot = new Robot();
        } catch (AWTException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        Random random = new Random();
        while (stop<=30) {
            robot.mouseMove(random.nextInt(500), random.nextInt(500));
            stop++;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }                
        }               
    }

Program that shuts down the computer (possibly have to change the values due to resolution)

public static  void desligaPc(){
    Robot robot = null;
    try {
        robot = new Robot();
    } catch (AWTException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

        robot.mouseMove(0, 800);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseMove(300, 700);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);            
    }    
}
  • Thank you for the examples!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.