一.代码如下
import java.awt.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class MyMouse{
public static void main(String[] args) throws AWTException {
Robot myRobot = new Robot();
//设置x和y值初始为0、可以方便理解成int x = 0;这样
AtomicInteger x = new AtomicInteger(0);
AtomicInteger y = new AtomicInteger(0);
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable task = () -> {
// 获取当前鼠标位置
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
//如果当前鼠标位置和上次不同、代表鼠标移动过、不做任何处理
if(mouseLocation.x != x.get() && mouseLocation.y != y.get()) {
x.set(mouseLocation.x);
y.set(mouseLocation.y);
}else {
//相反代表鼠标未移动过、偷偷将当前鼠标像素值减一
myRobot.mouseMove(x.addAndGet(-1),y.get());
}
System.out.println("("+x.get()+","+y.get()+")");
};
//80秒判断一次,假如自动熄屏时间3分钟,那秒数应设置为180s/2再额外减去代码运行带来干扰的几秒
executor.scheduleAtFixedRate(task, 0, 80, TimeUnit.SECONDS);
}
}
逻辑:80秒判定一次,若当前鼠标位置和上次判定位置相同、代表80s内未移动鼠标、鼠标x值减一。若和上次判定位置不同、则不做任何操作。
(实际使用不会受到干扰、除非第二次判定时正在滑动鼠标、碰巧判定的那一瞬间鼠标正好划过了第一次判定的位置、此时会将鼠标拉回到第一次判定位置左边减一像素的位置)
二.使用运行
1)我新建了D盘下的work目录
2)在work目录下新建名为MyMouse.txt文本文件,将上述代码粘贴后更名为MyMouse.java
3)打开CMD命令行执行 javac D:\work\MyMouse.java 自动生成MyMouse.class文件
4)再新建start.txt文件,添加一行
javaw -classpath D:\work MyMouse
后更改start.txt 为start.bat
需要运行脚本时双击start.bat就可以了,启动的命令行窗口可以关闭
关机后服务自动停止、或者去任务管理器里停止