直接进入问题,我试图在我的主程序中实现屏幕/显示/显示器的关闭和打开功能。我研究了一下,发现这个答案很有趣。所以,尝试测试一下。简而言之,这是代码:
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)
屏幕关闭效果很好,但在执行屏幕打开功能时,屏幕仅打开一秒钟,然后又立即关闭。我现在甚至无法解释为什么会发生这种情况!
也尝试了这种更原始的方法,但这里也存在同样的问题:
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()
这里是另一个参考链接,可能会有所帮助。
屏幕关闭时有 github 存储库,就像这个,但屏幕上没有!
请建议我是否有任何修复此问题或其他更好的方法来打开/关闭屏幕?
这并不是问题的实际解决方案,它一打开就打开,但我找到了一种方法让它不会关闭。
不是一个很好的方法,但它有效
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()
如果您移动光标或键入内容,屏幕将保持打开状态,所以
有一个名为 monitorcontrol 的 python 包,您可以使用它来控制显示器电源模式、对比度、输入源和亮度(亮度)。 以下是打开和关闭显示器电源的示例:
from monitorcontrol import get_monitors
from time import sleep
for monitor in get_monitors():
with monitor:
monitor.set_power_mode(4) # soft off
sleep(3)
monitor.set_power_mode(1) # on
如果您想使用 ctypes 而不是此软件包,请参阅 此答案 使用 ctypes 和 windows 监视器 api 打开和关闭监视器