Simulate alt+tab in Python

11,280

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.

Share:
11,280
Hugo Salvador
Author by

Hugo Salvador

I had made things using Turbo Pasca, Visual Basic, VBA and C#, but I've been focusing on Python since 2009.

Updated on June 04, 2022

Comments

  • Hugo Salvador
    Hugo Salvador almost 2 years

    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?