Java robot 控制桌面鼠标键盘

Administrator
发布于 2019-05-22 / 776 阅读
0
0

Java robot 控制桌面鼠标键盘

接着之前创建dll通过JNI来获取当前桌面程序坐标的代码。

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WindowsUtil {
	Robot robot;
	Map<String, Integer> keyMap;
	static {
		System.loadLibrary("WindowsUtil");
	}

	public WindowsUtil() throws AWTException {
		robot = new Robot();
		robot.setAutoDelay(500);  //这是动作延迟,即之前的一个动作完成之后延迟*毫秒再执行下一个动作

		keyMap = new HashMap<String, Integer>(); //存放常用字符
		keyMap.put("a", KeyEvent.VK_A);
		keyMap.put("b", KeyEvent.VK_B);
		keyMap.put("c", KeyEvent.VK_C);
		keyMap.put("d", KeyEvent.VK_D);
		keyMap.put("e", KeyEvent.VK_E);
		keyMap.put("f", KeyEvent.VK_F);
		keyMap.put("g", KeyEvent.VK_G);
		keyMap.put("h", KeyEvent.VK_H);
		keyMap.put("i", KeyEvent.VK_I);
		keyMap.put("j", KeyEvent.VK_J);
		keyMap.put("k", KeyEvent.VK_K);
		keyMap.put("l", KeyEvent.VK_L);
		keyMap.put("m", KeyEvent.VK_M);
		keyMap.put("n", KeyEvent.VK_N);
		keyMap.put("o", KeyEvent.VK_O);
		keyMap.put("p", KeyEvent.VK_P);
		keyMap.put("q", KeyEvent.VK_Q);
		keyMap.put("r", KeyEvent.VK_R);
		keyMap.put("s", KeyEvent.VK_S);
		keyMap.put("t", KeyEvent.VK_T);
		keyMap.put("u", KeyEvent.VK_U);
		keyMap.put("v", KeyEvent.VK_V);
		keyMap.put("w", KeyEvent.VK_W);
		keyMap.put("x", KeyEvent.VK_X);
		keyMap.put("y", KeyEvent.VK_Y);
		keyMap.put("1", KeyEvent.VK_1);
		keyMap.put("2", KeyEvent.VK_2);
		keyMap.put("3", KeyEvent.VK_3);
		keyMap.put("4", KeyEvent.VK_4);
		keyMap.put("5", KeyEvent.VK_5);
		keyMap.put("6", KeyEvent.VK_6);
		keyMap.put("7", KeyEvent.VK_7);
		keyMap.put("8", KeyEvent.VK_8);
		keyMap.put("9", KeyEvent.VK_9);
		keyMap.put("0", KeyEvent.VK_0);
	}

	public native String getXY(String title);

	public List<String[]> getInstances() {
		List<String[]> list = new ArrayList<String[]>();
		String[] ss = getXY("123").split("\n");
		for (String s : ss) {
			String[] sss = s.split("\\?\\?\\?");
			if (sss[0].indexOf("Eclipse IDE") != -1) {
				String[] ssss = sss[1].trim().split(" ");
				list.add(ssss);
			}
		}
		return list;
	}

	public void moveM(int x, int y) {
		robot.mouseMove(x, y);
	}

	public void leftClick() {
		robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
		robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
	}

	public void keyPress(String keys) {
		for (char c : keys.toCharArray()) {
			int key = keyMap.get(String.valueOf(c));
			robot.keyPress(key);
			robot.keyRelease(key);
		}
	}

	public static void main(String[] args) throws AWTException {
		WindowsUtil util = new WindowsUtil();
		for (String[] ss : util.getInstances()) {
			for (String s : ss) {
				System.out.println(s);
			}
			util.moveM(Integer.valueOf(ss[0]) + 500, Integer.valueOf(ss[3]) + 500);
			util.leftClick();
			util.keyPress("123456qwetrt");
		}
	}
}


评论