使用Java/Python提高工作效率01-Java Robot类
用Java实现可重复性的鼠标键盘事件--Robot类的使用
Robot类的定义:
构建
Robot() // 在初始屏幕的坐标系上构建一个Robot类
Constructs a Robot object in the coordinate system of the primary screen.
Robot(GraphicsDevice screen) // 在特定屏幕上创建
Creates a Robot for the given screen device.
方法总结
| 返回值和返回类型 | 方法 | 描述 |
|---|---|---|
| BufferedImage | createScreenCapture(Rectangle screenRect) | 创建包含从屏幕读取的像素的图像。 |
| void | delay(int ms) | 特定时间段休眠时间 |
| int | getAutoDelay() | 返回执行某一事件后Robot的休眠时间 |
| Color | getPixelColor(int x, int y) | 返回当前坐标值的像素颜色 |
| boolean | isAutoWaitForIdle() | 返回此机器人在生成事件后是否自动调用waitForIdle |
| void | keyPress(int keycode) | 模拟按下键盘按键 |
| void | keyRelease(int keycode) | 模拟释放键盘按键 |
| void | mousePress(int buttons) | 模拟按下鼠标按钮 |
| void | mouseRelease(int buttons) | 模拟释放鼠标按钮 |
| void | mouseWheel(int wheelAmt) | 模拟鼠标滚轮事件 |
| void | setAutoDelay(int ms) | 设置此Robot在生成事件后休眠的毫秒数 |
| void | setAutoWaitForIdle(boolean isOn) | 设置此机器人在生成事件后是否自动调用waitForIdle |
| String | toString() | 返回此Robot的字符串表示形式 |
| void | waitForIdle() | 等待直到事件队列上当前的所有事件都已处理 |
案例
键盘事件,模拟打字
public class Keyboard {
public static void main(String[] a) throws AWTException{
System.out.print("Hello World");
Robot robot = new Robot();
robot.delay(5000);
robot.keyPress(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_W);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_D);
robot.delay(100);
robot.keyPress(KeyEvent.VK_ENTER);
}
}
鼠标事件,模拟鼠标来回移动
public class Mouse {
public static void main(String[] args) throws AWTException{
System.out.print("Mouse Move");
Robot robot = new Robot();
robot.delay(1000);
int y = 500;
int n = 0;
do {
for(int x=0; x<3840; x++) {
robot.mouseMove(x, y);
}
for(int x=0; x<3840; x++) {
robot.mouseMove(3840- x, y);
}
n++;
}while(n<50);
}
}

浙公网安备 33010602011771号