import java.awt.Robot;
import java.util.Random;
public class MouseMover {
public static final int FIVE_SECONDS = 5000;
public static final int MAX_Y = 400;
public static final int MAX_X = 400;
public static void main(String... args) throws Exception {
Robot robot = new Robot();
Random random = new Random();
while (true) {
robot.mouseMove(random.nextInt(MAX_X), random.nextInt(MAX_Y));
Thread.sleep(FIVE_SECONDS);
}
}
}
import java.awt.*;
public class MouseJiggle {
public static final int SLEEP_MILLIS = 60*1000;
public static void main(String... args) throws Exception {
Robot robot = new Robot();
while (true) {
Point point = MouseInfo.getPointerInfo().getLocation();
robot.mouseMove(point.x, point.y);
System.out.println("Mouse Moved!!");
Thread.sleep(SLEEP_MILLIS);
}
}
}
public class WindowsStayAwake {
public static final int ES_AWAYMODE_REQUIRED = 0x00000040;
public static final int ES_CONTINUOUS = 0x80000000;
public static final int ES_DISPLAY_REQUIRED = 0x00000002;
public static final int ES_SYSTEM_REQUIRED = 0x00000001;
public static final int ES_USER_PRESENT = 0x00000004;
public static int setThreadExecutionState(int esFlags) {
int result = Kernel32.INSTANCE.SetThreadExecutionState(esFlags);
if (result == 0)
throw new IllegalArgumentException("Failed to set thread execution state to: " + toHexString(esFlags));
return result;
}
private static String toHexString(int i) {
StringBuilder builder = new StringBuilder("0x");
builder.append(Integer.toHexString(i));
while (builder.length() < 10)
builder.append('0');
return builder.toString();
}
private static interface Kernel32 extends Library {
public static Kernel32 INSTANCE = Native.load("Kernel32", Kernel32.class,
Collections.<String, Object>emptyMap());
public int SetThreadExecutionState(int esFlags);
}
}
这里有一个服务,它会定期调用函数来防止显示器关闭:
public class StayAwakeService {
private static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
private static ScheduledFuture<?> scheduledFuture;
private static boolean isRunning = false;
public static void start(Duration duration) {
if (isRunning)
return;
// Prevent the display from turning off.
int option = WindowsStayAwake.ES_DISPLAY_REQUIRED;
scheduledFuture = executorService.scheduleAtFixedRate(() -> WindowsStayAwake.setThreadExecutionState(option), 0,
duration.getSeconds(), TimeUnit.SECONDS);
isRunning = true;
}
public static void stop() {
scheduledFuture.cancel(false);
isRunning = false;
}
}
2条答案
按热度按时间hwamh0ep1#
搜索解决方案时发现:
https://code.joejag.com/2013/move-your-mouse-pointer-with-java.html
然而,它对我不太起作用,因为它会随机移动鼠标指针,这意味着我只能在不使用电脑的时候使用这个应用程序
https://code.joejag.com/2013/move-your-mouse-pointer-with-java.html
我修改了解决方案以更好地满足我的需求:
此版本获取鼠标指针的当前位置并将鼠标移动到它已经在的位置。从用户的Angular 来看,鼠标不会移动,但它确实可以防止计算机空闲。
dbf7pr2w2#
如果你使用的是Windows,你可以调用原生的
kernel32.dll
函数SetThreadExecutionState
来防止计算机休眠。这是我使用JNA的方法:这里有一个服务,它会定期调用函数来防止显示器关闭: