How to start the Windows screensaver from Python?

86 Views Asked by At

How to launch the Windows screensaver from Python ?

I have tried methods like

import subprocess
subprocess.Popen("C:\Windows\System32\scrnsave.scr")

it starts a screensaver, but it doesn't start the screensaver that has been configured in the Windows control panel.

PS: there are a few questions tagged [screensaver] + [windows] + [python], but I haven't found a question+answer specific to Windows with Python, so here is Q+A post.

1

There are 1 best solutions below

0
Basj On

You can launch the screensaver with:

import ctypes
WM_SYSCOMMAND = 0x0112
SC_SCREENSAVE = 0xF140
ctypes.windll.user32.SendMessageA(ctypes.windll.user32.GetDesktopWindow(), WM_SYSCOMMAND, SC_SCREENSAVE, 0)

Here is another working solution:

import os, win32com.client
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(".", "root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Desktop")
for objItem in colItems:
    if objItem.ScreenSaverExecutable:
        os.system(objItem.ScreenSaverExecutable + " /start")
        break