Skip to content

Instantly share code, notes, and snippets.

@takehaya
Created December 13, 2024 17:31
Show Gist options
  • Save takehaya/13924b6f1cdfbece328c78e035250375 to your computer and use it in GitHub Desktop.
Save takehaya/13924b6f1cdfbece328c78e035250375 to your computer and use it in GitHub Desktop.
勝手にスクリーンセイバーが動いてしまうのを阻止するためにプログラム。3時間マウスを触らなかったらこのプログラムは落ちるように設計されてる
import time
import Quartz.CoreGraphics as CG
def get_mouse_position():
"""現在のマウス位置を取得"""
current_pos = CG.CGEventGetLocation(CG.CGEventCreate(None))
return (current_pos.x, current_pos.y)
def move_mouse():
"""マウスを一時的に動かして戻す"""
current_pos = get_mouse_position()
# 新しい位置(右に5ピクセル動かす)
new_pos = (current_pos[0] + 5, current_pos[1])
# マウスを右に動かし、元の位置に戻す
move_event = CG.CGEventCreateMouseEvent(None, CG.kCGEventMouseMoved, new_pos, CG.kCGMouseButtonLeft)
CG.CGEventPost(CG.kCGHIDEventTap, move_event)
return_event = CG.CGEventCreateMouseEvent(None, CG.kCGEventMouseMoved, current_pos, CG.kCGMouseButtonLeft)
CG.CGEventPost(CG.kCGHIDEventTap, return_event)
def prevent_screensaver(interval=60, max_inactivity=3 * 60 * 60): # 3 hours操作しなかったらアプリを終了させてスリープableにする
"""
ユーザーのマウス操作が一定時間ない場合に終了する。
interval: マウスを動かす間隔(秒)
max_inactivity: 最大非操作時間(秒)
"""
print(f"Starting mouse movement every {interval} seconds to prevent screensaver...")
last_mouse_position = get_mouse_position()
last_activity_time = time.time()
try:
while True:
# 現在のマウス位置を取得
current_mouse_position = get_mouse_position()
# マウス位置が変わった場合、最後のアクティビティ時間を更新
if current_mouse_position != last_mouse_position:
last_activity_time = time.time()
last_mouse_position = current_mouse_position
# 非操作時間を計算
inactivity_duration = time.time() - last_activity_time
# 最大非操作時間を超えた場合プログラムを終了
if inactivity_duration >= max_inactivity:
print("No mouse activity detected for 3 hours. Stopping mouse movement.")
break
# マウスを動かす
move_mouse()
time.sleep(interval)
except KeyboardInterrupt:
print("Stopping mouse movement due to user interruption.")
if __name__ == "__main__":
prevent_screensaver()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment