Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Periodically moves the mouse pointer
package com.dustinredmond.movemouse;
import java.awt.*;
/**
* Moves mouse one pixel at a time, barely noticeable to the end user,
* useful for preventing the PC going to sleep. I had a Linux box that
* for some reason would still go to sleep, even with correct settings...
*
* Pass as an argument the number of seconds between mouse moves (an integer number).
* If nothing is passed, the default of 5 seconds will apply.
*/
public class MoveMouse {
public static void main(String[] args) {
// Get number of seconds between delay,
// default to 5 if nothing passed
int delaySeconds = 5;
if (args.length > 0) {
delaySeconds = Integer.parseInt(args[0]);
}
System.out.printf("Mouse movement initiated, " +
"moving mouse every %s seconds.", delaySeconds);
try {
// Change each iteration so there is no
// net change of mouse position after
// two iterations
boolean flip = false;
//noinspection InfiniteLoopStatement
while (true) {
Robot r = new Robot();
r.delay(1000 * delaySeconds);
// current mouse positions
int x = (int) MouseInfo.getPointerInfo().getLocation().getX();
int y = (int) MouseInfo.getPointerInfo().getLocation().getY();
// move left/right up/down depending on the iteration cycle
r.mouseMove(flip ? x + 1 : x - 1, flip ? y + 1 : y - 1);
flip = !flip;
}
} catch (AWTException e) {
throw new RuntimeException("Unable to initiate. Make sure that you are not" +
" running in a headless environment.", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment