I need to make a macro, capturing mouse and keyboard. How should I proceed in JAVA? do I need a specific API?
I need to make a macro, capturing mouse and keyboard. How should I proceed in JAVA? do I need a specific API?
If I understood correctly, the idea of doing a Macro would be to automate a task, as if it were a user using the computer.
The Java API makes the class Robot
for that. It contains methods that trigger simple events such as mouseMove
, mousePress
and keyPress
.
For simple task automation, it should work fine. However, the documentation warns that some systems may require special permissions to work.
I do not know this API very well, so I can not tell you what the limitations and problems are.
If you need something more elaborate you can try a third-party API, such as jNativeHook , which provides a Java API interface with native methods of the Operating System API. In fact, the idea is the same as the Robot
class, but they promise more functionality.
Just to complete the response from @utluiz
Some practical examples of using these functions:
Uncontrolled mouse walks randomly across 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 off the computer (possibly should have to change 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);
}
}