JAVA按键精灵,模拟点击
主要方法:
// 创建Robot对象
java.awt.Robot r = new java.awt.Robot();
// 将鼠标指针移动到坐标(x,y)
r.mouseMove(x, y);
// 鼠标按下某个键
r.mousePress(InputEvent.BUTTON1_MASK);
// 暂停ms毫秒
r.delay(ms)
// 鼠标松开某个键
r.mouseRelease(InputEvent.BUTTON1_MASK);
//按下键盘某个键
r.keyPress(KeyEvent.VK_A);
//松开键盘某个键
r.keyRelease(KeyEvent.VK_A);
package com.goma.keysprite; import java.awt.Robot; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Vector; /** * 支持脚本文件的按键控制程序 */ public class KeySprite { public static void main(String[] args) { String filename = System.getProperty("user.dir")+"\\src\\com\\goma\\keysprite\\test.t"; try { Vector<String> v = readFile(filename);//读取配置文件 parseVector(v);//执行文件 } catch (IOException e) { System.out.println("配置文件错误"); } catch (Exception e) { System.out.println("其他错误"); } } /** * 读取文件到Vector中 * @param filepath文件路径 */ public static Vector<String> readFile(String filepath) throws IOException { Vector<String> v = new Vector<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filepath))); String s = br.readLine(); while (s != null) { v.add(s); s = br.readLine(); } br.close(); return v; } /** * 解析读到的Vector,并执行对应的操作 * @param v Vector对象 */ public static void parseVector(Vector<String> v) { int size = v.size(); try { Robot r = new Robot(); for (int i = 0; i < size; i++) { String s = (String) v.get(i); String[] data = s.split(" "); if (data[0].equals("移动")) { int x = Integer.parseInt(data[1]); int y = Integer.parseInt(data[2]); r.mouseMove(x, y); } else if (data[0].equals("按键")) { String c = data[1].charAt(0)+""; if("L".equals(c)){ r.mousePress(InputEvent.BUTTON1_MASK); r.mouseRelease(InputEvent.BUTTON1_MASK); }else{ r.mousePress(InputEvent.BUTTON3_MASK); r.mouseRelease(InputEvent.BUTTON3_MASK); } } else if (data[0].equals("暂停")) { int time = Integer.parseInt(data[1]); r.delay(time); }else if(data[0].equals("录入")){//测试可忽略 System.out.println("录入"); r.keyPress(KeyEvent.VK_G); r.keyRelease(KeyEvent.VK_G); r.keyPress(KeyEvent.VK_O); r.keyRelease(KeyEvent.VK_O); r.keyPress(KeyEvent.VK_M); r.keyRelease(KeyEvent.VK_M); r.keyPress(KeyEvent.VK_A); r.keyRelease(KeyEvent.VK_A); } } } catch (Exception e) { e.printStackTrace(); } } }
暂停 3000 移动 441 255 按键 L 暂停 1000 录入 暂停 1000 移动 890 255 按键 L