Java 自动按键,以及cmd脚本调用

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xyjincan/article/details/77529037

使用Java 的辅助测试按键模块

Java代码

Robot,KeyEvent

main.java


import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;

public class Main {

    public static void main(String[] args) throws Exception {
        int[] keys = new int[args.length];
        for(int i=0;i<args.length;i++) {
            keys[i] = getValue(args[i]);
        }
        PressKeyUtils pku = new PressKeyUtils();
        pku.Press(keys);
    }

    public static int getValue(String key) {
        Class<KeyEvent>  clazz = KeyEvent.class;
        try {
            Field field = clazz.getField("VK_"+key.toUpperCase());
            return field.getInt(null);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return -1;
    }

}

class PressKeyUtils {

    Robot r = null;

    public PressKeyUtils() {
        try {
            r = new Robot();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    // ctrl+ key art + key
    public void Press(int... keys) {
        for(int key:keys) {
            if(key==-1) {
                new Exception("按键不支持:").printStackTrace();
                return;
            }
        }
        try {
            r = new Robot();
            int beginIndex=0;
            for (;beginIndex<keys.length;beginIndex++) {
                r.keyPress(keys[beginIndex]);
            }
            int endIndex = keys.length - 1;
            for (; endIndex >= 0; endIndex--) {
                r.keyRelease(keys[endIndex]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

场景

脚本自动打开文件,并确认、保存

aoto.bat

start /b doc.docx
java -jar AutoTab.jar tab                           
java -jar AutoTab.jar tab
java -jar AutoTab.jar enter
:: 等待十秒后,继续向下执行
choice /t 10 /d y /n >nul
java -jar AutoTab.jar control s
展开阅读全文

没有更多推荐了,返回首页