java 机器人类的使用

java语言很强大。强大到让人害怕嘻嘻,这或许就是开源的力量吧。闲话不多说我们java中提供了一个做自动化测试的类,那就是Robot类。

我们下来看一下官方是怎么说的。

This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations. 
Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events. 

Note that some platforms require special privileges or extensions to access low-level input control. If the current platform configuration does not allow input control, an AWTException will be thrown when trying to construct Robot objects. For example, X-Window systems will throw the exception if the XTEST 2.2 standard extension is not supported (or not enabled) by the X server. 

Applications that use Robot for purposes other than self-testing should handle these error conditions gracefully.

大概的意思呢就是我们java提供了一个类这个类是干啥的,都能做啥。


大概看一下这个都有哪些方法。

下面我们做一些简单的操作。

来来上代码。

	public static void main(String[] args) throws IOException, InterruptedException, AWTException {
		// 使用java代码去启动一个程序

		Process p = java.lang.Runtime.getRuntime().exec("C:\\Windows\\system32\\notepad.exe");
		Thread.sleep(1100);
		Robot robot = new Robot();

		robot.keyPress(KeyEvent.VK_L); // 按下l键
		robot.keyPress(KeyEvent.VK_S); // 按下s键
                robot.keyPress(KeyEvent.VK_ENTER); //按下回车键
	}

实现屏幕截图操作

//获取屏幕分辨率
				Thread.sleep(1100);
		        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		        System.out.println(d);
		        //截图
		        Rectangle screenRect = new Rectangle(d);
		        BufferedImage bufferedImage = robot.createScreenCapture(screenRect);
		        //保存截图
		        File file = new File("C:\\Users\\Administrator\\Desktop\\123.png");
		        ImageIO.write(bufferedImage, "png", file);

猜你喜欢

转载自blog.csdn.net/qq_38318622/article/details/80583313