在 Python 中模拟 alt+tab

Hug*_*dor 5 python ctypes

我在 Windows 8.1 中运行此代码:

import ctypes, time

ctypes.windll.user32.keybd_event(0x12, 0, 0, 0) #Alt
ctypes.windll.user32.keybd_event(0x09, 0, 0, 0) #Tab

time.sleep(2)

ctypes.windll.user32.keybd_event(0x09, 0, 2, 0) #~Tab
ctypes.windll.user32.keybd_event(0x12, 0, 2, 0) #~Alt
Run Code Online (Sandbox Code Playgroud)

我希望这段代码模拟按住 Alt 键,按住 Tab 键,等待 2 秒,松开 Tab 键,然后松开 Alt 键,但它不起作用。代码无法按住按键,只需脉冲(按下并松开)按键即可。

我以前试过这个代码并且工作,但不是在 Windows 8.1 中。我能做什么?

smi*_*els 6

这是一个稍微紧凑的 alt-tab 方法。

import pyautogui,time

pyautogui.keyDown('alt')
time.sleep(.2)
pyautogui.press('tab')
time.sleep(.2)
pyautogui.keyUp('alt')
Run Code Online (Sandbox Code Playgroud)

重复 pyautogui.press('tab') 您想要移动的次数,正如 userNo99 提到的,您需要包含一些 time.sleep(.2) 以在您的操作之间创建延迟。

  • 更好的方法是使用“热键”功能。您还可以提供一个时间间隔来模拟“time.sleep()”。`pyautogui.hotkey("alt", "tab", 间隔=0.2)`。查看[文档](https://pyautogui.readthedocs.io/en/latest/keyboard.html#the-hotkey-function) (2认同)

小智 0

这可行,但 alt 和 tab 之间也必须有延迟。

from time import sleep
import ctypes

user32 = ctypes.windll.user32

user32.keybd_event(0x12, 0, 0, 0) #Alt
sleep(1)
user32.keybd_event(0x09, 0, 0, 0) #Tab
sleep(1)
user32.keybd_event(0x09, 0, 2, 0) #~Tab
sleep(0.1)
user32.keybd_event(0x12, 0, 2, 0) #~Alt
Run Code Online (Sandbox Code Playgroud)

应该管用。