Key Presses in Python

Key Presses in Python

Install the pywin32 extensions. Then you can do the following:

import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want

Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start here, perhaps.

EDIT: Sending F11

import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")

# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")

How do I detect multiple keypresses in python all at the same time?

The best approach to do it is to use pygame module. pygame.key.get_pressed() returns the list of all the keys pressed at one time:

e.g. for multiple key press

keys = pygame.key.get_pressed()
if keys[pygame.K_w] and keys[pygame.K_a]:
#Do something

More details in documentation.

Is there any way to detect key press in Python?

Assuming you want a command line application
you should be able to do it with

import sys
import termios
import tty
custom_messages = {'a': 'some other message'}
custom_messages['b'] = 'what?';
stdin = sys.stdin.fileno()
tattr = termios.tcgetattr(stdin)
try:
tty.setcbreak(stdin, termios.TCSANOW)
while True:
char = sys.stdin.read(1)
print(custom_messages.get(char, 'You pressed ' + char))
except KeyboardInterrupt:
print('You interrupted')
sys.exit() ## ?
finally:
termios.tcsetattr(stdin, termios.TCSANOW, tattr)

I based my answer on disabling buffering in stdin

How to simulate key press in a specific chrome tab\window

Unfortunately, PyAutoGUI can't do this because it only blindly clicks on the screen at x, y coordinates. Unless you know the coordinates of the tab, you won't be able to put it in focus and send key presses to the window.

I recommend a library like Selenium for doing GUI automation in web browsers.

Capture all keypresses of the system with Tkinter

Solution 1: if you need to catch keyboard events in your current window, you can use:

from tkinter import *

def key_press(event):
key = event.char
print(f"'{key}' is pressed")

root = Tk()
root.geometry('640x480')
root.bind('<Key>', key_press)
mainloop()

Solution 2: if you want to capture keys regardless of which window has focus, you can use keyboard

Looping until a specific key is pressed

Here is a solution which works:

import keyboard
import time
import threading

class main:
def __init__(self):
# Create a run variable
self.run = True

# Start main thread and the break thread
self.mainThread = threading.Thread(target=self.main)
self.breakThread = threading.Thread(target=self.breakThread)

self.mainThread.start()
self.breakThread.start()

def breakThread(self):
print('Break thread runs')
# Check if run = True
while True and self.run == True:
if keyboard.is_pressed('esc'):
self.newFunction()

def main(self):
print('Main thread runs')

# Also check if run = True
while not keyboard.is_pressed('esc') and self.run:
print('test')
time.sleep(2)

# Break like this
if keyboard.is_pressed('esc'):
break

print('test')
time.sleep(2)

def newFunction(self):
self.run = False
print('You are in the new function!')

program = main()


Related Topics



Leave a reply



Submit