24

I tried to use this script to prevent windows screen lock. The script works for moving the mouse, but it doesn't prevent windows 10 from locking.

import pyautogui
import time
import win32gui, win32con
import os

Minimize = win32gui.GetForegroundWindow()
win32gui.ShowWindow(Minimize, win32con.SW_MINIMIZE)

x = 1

while x == 1:
    pyautogui.moveRel(1)
    pyautogui.moveRel(-1)
    time.sleep (300)
Python account
  • 427
  • 1
  • 5
  • 15
  • I don't know about Pyauto, but the screen lock *can* be prevented simply by moving the mouse. I wrote a script using Java's robot library that randomly moves the mouse by one pixel every minute. It was able to delay the lock indefinitely. – Carcigenicate Oct 07 '19 at 16:21
  • Try more than one pixel and maybe use `moveTo` vs `moveRel`? – zglin Oct 07 '19 at 17:29
  • 1
    @zhqiat I attempted to do this with moveTo at 50 pixel distance and it did not work. – Self Dot Aug 17 '20 at 15:30

2 Answers2

24

Yes it can. But sadly not by moving mouse which I don't know why and would like to know. So, my suggestion is to use pyautogui KEYBOARD EVENTS if possible. I have solved my problems by using VOLUME-UP & VOLUME-DOWN keys. Example code is provided below:

import pyautogui
import time

while True:
    pyautogui.press('volumedown')
    time.sleep(1)
    pyautogui.press('volumeup')
    time.sleep(5)

You can use any other keys if you want.

Shahriar Rahman Zahin
  • 624
  • 1
  • 11
  • 23
11
import ctypes

# prevent
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
# set back to normal
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)

https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate

Tested on python 3.9.1, win 10 64bit

Dániel Nagy
  • 111
  • 1
  • 3
  • 1
    thank you for this post. it took me a while to figure out 0x80000002 actually came from 0x8000000) + 0x00000002. Just in case this may help other folks – oldpride Aug 04 '22 at 16:20