0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

マウスジグラーをJavaで作る

Posted at

目的

定期的にマウスカーソルを動かして、スクリーンセーバーの起動を阻止します

使い方

起動して10秒後にマウスの位置を記録し、適当にマウスカーソルを動かして元の位置に戻ります。

移動の方向や時間間隔は適当に調整してください。

コード

package hello.mouse;
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class MouseMover {
	private static boolean running = true;
	public static void main(String[] args) {
		try {
			Robot robot = new Robot();
			JFrame frame = new JFrame("Mouse Mover");
			frame.setSize(640, 480);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setVisible(true);

			// キーリスナーを設定してEscキーで停止する
			frame.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
						running = false;
						frame.dispose();
					}
				}
			});

			int moveDistance = 100; // 移動距離(ピクセル)
			int delay = 3000; // 1秒間隔(ミリ秒)

			for (int n = 0; n < 10; n++) {
				System.err.println((10 - n));
				Thread.sleep(1000);
			}

			// 初期位置を取得
			Point initialPos = MouseInfo.getPointerInfo().getLocation();

			while (running) {
				Point currentPos = initialPos;

				// 元の位置に戻す
				robot.mouseMove(initialPos.x, initialPos.y);
				Thread.sleep(delay);
				if (running == false) {
					break;
				}
				// マウスを上に移動
				robot.mouseMove(currentPos.x, currentPos.y - moveDistance);
				Thread.sleep(delay);
				if (running == false) {
					break;
				}
				// マウスを右に移動
				robot.mouseMove(currentPos.x + moveDistance,
						currentPos.y - moveDistance);
				Thread.sleep(delay);
				if (running == false) {
					break;
				}
				// マウスを下に移動
				robot.mouseMove(currentPos.x + moveDistance, currentPos.y);
				Thread.sleep(delay);
				if (running == false) {
					break;
				}
				// マウスを左に移動
				robot.mouseMove(currentPos.x, currentPos.y);
				Thread.sleep(delay);
				if (running == false) {
					break;
				}
				// マウスを元の位置に戻す
				robot.mouseMove(currentPos.x, currentPos.y);
				Thread.sleep(delay);
				if (running == false) {
					break;
				}
			}
		} catch (AWTException | InterruptedException e) {
			e.printStackTrace();
		}
	}

}


以上.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?