在Python中,你可以使用`pyautogui`或`ctypes`库来锁定屏幕。以下是使用`pyautogui`库的示例代码:
```python
import os
import pyautogui
import time
def lock_screen():
执行锁屏命令
os.system("rundll32.exe user32.dll,LockWorkStation")
def auto_lock_screen(delay_in_seconds):
print(f"将在 {delay_in_seconds} 秒后自动锁屏...")
time.sleep(delay_in_seconds)
print("执行锁屏操作...")
lock_screen()
指定延迟时间(秒)
delay_seconds = 3
调用函数执行自动锁屏操作
auto_lock_screen(delay_seconds)
如果你使用的是Windows系统,并且想要通过调用Windows API来锁定屏幕,可以使用`ctypes`库,如下所示:
```python
import ctypes
from ctypes.wintypes import *
HWND_BROADCAST = 0xffff
WM_SYSCOMMAND = 0x0112
SC_MONITORPOWER = 0xF170
MonitorPowerOff = 2
SW_SHOW = 5
def lock_screen_api():
使用ctypes调用Windows API来锁定屏幕
windll.user32.PostMessageW(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MonitorPowerOff)
if __name__ == "__main__":
lock_screen_api()