Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate alt+tab in Python

Tags:

python

ctypes

I'm running in Windows 8.1 this code:

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

I expected this code simulate hold the Alt key, hold the Tab key, wait 2 seconds, release Tab key, then release Alt key, but it's not working. The code can't hold the keys, just pulse (press and release) the key.

I've tried this code before and worked, but not in Windows 8.1. What can I do?

like image 540
Hugo Salvador Avatar asked Nov 07 '16 13:11

Hugo Salvador


1 Answers

Here's a slightly tighter alt-tab method.

import pyautogui,time

pyautogui.keyDown('alt')
time.sleep(.2)
pyautogui.press('tab')
time.sleep(.2)
pyautogui.keyUp('alt')

Repeat pyautogui.press('tab') for the number of times you want to move over, and as userNo99 mentioned you'll want to include some time.sleep(.2)'s to create a delay in between your actions.

like image 146
smithNiels Avatar answered Oct 23 '22 10:10

smithNiels