这里模拟 Win + Ctrl + L 组合键
1、ctypes
ctypes库,它允许我们直接调用Windows API来模拟键盘输入。
bash
import ctypes
import time
# 定义所需的常量和结构
LONG = ctypes.c_long
DWORD = ctypes.c_ulong
ULONG_PTR = ctypes.POINTER(DWORD)
WORD = ctypes.c_ushort
class MOUSEINPUT(ctypes.Structure):
_fields_ = (("dx", LONG),
("dy", LONG),
("mouseData", DWORD),
("dwFlags", DWORD),
("time", DWORD),
("dwExtraInfo", ULONG_PTR))
class KEYBDINPUT(ctypes.Structure):
_fields_ = (("wVk", WORD),
("wScan", WORD),
("dwFlags", DWORD),
("time", DWORD),
("dwExtraInfo", ULONG_PTR))
class HARDWAREINPUT(ctypes.Structure):
_fields_ = (("uMsg", DWORD),
("wParamL", WORD),
("wParamH", WORD))
class INPUT(ctypes.Structure):
class _INPUT(ctypes.Union):
_fields_ = (("ki", KEYBDINPUT),
("mi", MOUSEINPUT),
("hi", HARDWAREINPUT))
_anonymous_ = ("_input",)
_fields_ = (("type", DWORD),
("_input", _INPUT))
# 定义按键代码
VK_LWIN = 0x5B
VK_CONTROL = 0x11
VK_L = 0x4C
# 定义SendInput函数
SendInput = ctypes.windll.user32.SendInput
SendInput.restype = ctypes.c_uint
SendInput.argtypes = [ctypes.c_uint, ctypes.POINTER(INPUT), ctypes.c_int]
# 创建INPUT结构
def create_input(vk, press):
return INPUT(type=1, ki=KEYBDINPUT(wVk=vk, wScan=0, dwFlags=0x0002 if not press else 0))
# 发送按键
def send_key_combo(keys):
inputs = [create_input(key, True) for key in keys]
inputs += [create_input(key, False) for key in reversed(keys)]
n_inputs = len(inputs)
array_type = INPUT * n_inputs
c_inputs = array_type(*inputs)
SendInput(n_inputs, c_inputs, ctypes.sizeof(INPUT))
# 等待5秒,确保系统已完全启动
time.sleep(5)
# 发送 Win + Ctrl + L 组合键
send_key_combo([VK_LWIN, VK_CONTROL, VK_L])
2、pyautogui
https://www.jianshu.com/p/3f5d0252f4a3
pyautogui库是一种用于自动化任务的强大工具,它可以模拟鼠标和键盘操作,执行各种GUI任务。无论是进行屏幕截图、自动填写表单、自动化测试还是进行GUI操作,pyautogui都可以派上用场。
安装
bash
pip install pyautogui
代码
bash
import pyautogui
import time
# 确保 pyautogui 库已安装
# 如果没有安装,可以使用以下命令进行安装:
# pip install pyautogui
# 为了确保按键按下的顺序正确,可以稍微延迟一下
time.sleep(2)
# 按下 Win 键
pyautogui.keyDown('win')
# 按下 Ctrl 键
pyautogui.keyDown('ctrl')
# 按下 L 键
pyautogui.keyDown('l')
# 释放 L 键
pyautogui.keyUp('l')
# 释放 Ctrl 键
pyautogui.keyUp('ctrl')
# 释放 Win 键
pyautogui.keyUp('win')