Last active
June 13, 2025 13:38
-
-
Save mageddo/ba7ac24e5ea6e6fd894aac9113b37f34 to your computer and use it in GitHub Desktop.
ScreenSaver Prevent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package poc; | |
import java.awt.MouseInfo; | |
import java.awt.Point; | |
import java.awt.Robot; | |
import java.awt.Toolkit; | |
import java.time.Duration; | |
import java.time.LocalDateTime; | |
/** | |
* Move the mouse by one pixel every {@link #MOUSE_MOVE_INTERVAL} to prevent screen saver, | |
* useful when you don't have the right permissions to change that. | |
* https://stackoverflow.com/questions/4231458/moving-the-cursor-in-java | |
* https://stackoverflow.com/questions/1439022/get-mouse-position | |
*/ | |
public class KeepMovingMouse { | |
public static final long MOUSE_MOVE_INTERVAL = Duration.ofSeconds(15) | |
.toMillis(); | |
public static void main(String[] args) { | |
try { | |
final Robot r = new Robot(); | |
for (; ; ) { | |
if (isMinuteEven()) { | |
moveMousePixel(r, 1); | |
} else { | |
moveMousePixel(r, -1); | |
} | |
Thread.sleep(MOUSE_MOVE_INTERVAL); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
private static boolean isMinuteEven() { | |
return LocalDateTime.now() | |
.getMinute() % 2 == 0; | |
} | |
static void moveMousePixel(Robot robot, int pixel) { | |
final var location = getCurrentLocation(); | |
final int x = (int) (location.getX() + pixel); | |
final int y = (int) (location.getY() + pixel); | |
robot.mouseMove(x, y); | |
System.out.printf("status=preventing-screen-saver, action=mouse-moved, y=%d, y=%d%n", x, y); | |
} | |
private static Point getCurrentLocation() { | |
return MouseInfo.getPointerInfo() | |
.getLocation(); | |
} | |
static void moveMouseToTheCenter(Robot robot) { | |
final int y = (int) Toolkit.getDefaultToolkit() | |
.getScreenSize() | |
.getHeight() / 2; | |
final int x = (int) Toolkit.getDefaultToolkit() | |
.getScreenSize() | |
.getWidth() / 2; | |
robot.mouseMove(x, y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment