09 September, 2007

OS input events generation

The simplest way to generate system input events (mouse and keyboard) is using Robot class from Java API.

Source code that listed below, moves mouse over the screen and presses mouse's button.


JRobot.java

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;

public class JRobot {
private Robot robot = null;

private Point point = new Point(0, 0);

private void relativeMouseMove(int x, int y) {
point.x+=x;
point.y+=y;
robot.mouseMove(point.x, point.y);
}

private JRobot() {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
return;
}
robot.setAutoDelay(1);

Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
relativeMouseMove(32, screen.height - 8);
robot.mousePress(InputEvent.BUTTON1_MASK);

for (int i = 0; i < 256; i++) {
relativeMouseMove(0, -1);
}
robot.delay(300);
robot.waitForIdle();
for (int i = 0; i < 256; i++) {
relativeMouseMove(1, 0);
}

}

public static void main(String[] args) {
new JRobot();
}
}



It is possible to use Robot for the various purposes ;-)

No comments: