pythonwindowswinapiscreenctypes

Turn screen on and off on Windows


Directly into the problem, I was trying to implement the screen/display/monitor Off and On feature into my primary program. I researched a bit and found this one answer interesting. So, tried testing it. Here's the code in a nutshell:

import time
import win32gui
import win32con

def ScreenOFF():
    """
    Function to turn off the screen.
    """
    return win32gui.SendMessage(win32con.HWND_BROADCAST,
                            win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, 2)

def ScreenON():
    """
    Function to turn on the screen.
    """
    return win32gui.SendMessage(win32con.HWND_BROADCAST,
                            win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, -1)

ScreenOFF()
time.sleep(5)
ScreenON()
time.sleep(5)

The Screen Off was working great but while executing the Screen On function, The Screen only turns on for a second and then again it turns off immediately. I could not even reason now why that happens !

Also tried this more primitive approach but here too is the same problem:

import time
import ctypes

def ScreenOFF():
    """
    Function to turn off the screen.
    """
    ctypes.windll.user32.SendMessageW(65535, 274, 61808, 2)

def ScreenON():
    """
    Function to turn on the screen.
    """
    ctypes.windll.user32.SendMessageW(65535, 274, 61808, -1)

ScreenOFF()
time.sleep(5)
ScreenON()

Here's another reference link that might help here.

There are github repos on screen off, like this one, but NONE on Screen On !

Please suggest me if there are any fixes to this or other better ways to turn the screen On/OFF ?


Solution

  • Not a actual solution to the issue where it just turns as soon as it turns on, but I found a way to keep it not going off.

    Not a very great way but it works

    import time
    import ctypes
    import win32api, win32con
    def screen_off():
        ctypes.windll.user32.SendMessageW(65535, 274, 61808, 2)
    def screen_on():
        ctypes.windll.user32.SendMessageW(65535, 274, 61808, -1)
        move_cursor()
    def move_cursor():
        x, y = (0,0)
        win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, x, y)
    
    screen_off()
    time.sleep(3)
    screen_on()
    

    If you move the cursor or type something the screen will stay on, so