java控制鼠标键盘类–Robot
Robot类用于为测试自动化、自运行演示程序和其他需要控制鼠标和键盘的应用程序生成本机系统输入事件。Robot 的主要目的是便于 Java 平台实现自动测试。
import java.awt.Robot; //包名
Robot robot = new Robot(); //实例化
robot.delay(10); //延迟
robot.mouseMove(x, y); //鼠标移动到指定的坐标
//鼠标左键点击(按下和抬起一起使用)
robot.mousePress(InputEvent.BUTTON3_MASK); //鼠标左键按下
robot.mouseRelease(InputEvent.BUTTON3_MASK); //鼠标左键抬起
//鼠标右键点击(按下和抬起一起使用)
robot.mousePress(InputEvent.BUTTON3_MASK); //鼠标右键按下
robot.mouseRelease(InputEvent.BUTTON3_MASK);//鼠标右键抬起
//键盘按下指定的键
robot.keyPress(KeyEvent.VK_A); //按下A键
//复制操作
robot.keyPress(KeyEvent.VK_CONTROL); //按下ctrl键
robot.keyPress(KeyEvent.VK_C); //按下C键
robot.keyRelease(KeyEvent.VK_CONTROL); //抬起ctrl键
robot.keyRelease(KeyEvent.VK_C); //抬起C键
//粘贴操作
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
//捕捉全屏幕(截屏)
BufferedImage fullScreenImage = robot.createScreenCapture(new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize()));
/**
* 捕捉屏幕的一个矫形区域
*
* @param r
* @param x
* x坐标位置
* @param y
* y坐标位置
* @param width
* 矩形的宽
* @param height
* 矩形的高
* @return
*/
public Icon capturePartScreen(Robot r, int x, int y, int width, int height) {
r.mouseMove(x, y);
BufferedImage fullScreenImage = r.createScreenCapture(new Rectangle(
width, height));
ImageIcon icon = new ImageIcon(fullScreenImage);
return icon;
}