External Exam Download Resources Web Applications Games Recycle Bin

Detecting Keydown key "A"

The remaining scripts will keep the console window displayed (not hidden). The following script will detect whether or not the "A" keyboard key is in the state of being pressed:

import ctypes #access Windows C functions
kernel32 = ctypes.windll.kernel32 #kernel level
user32 = ctypes.windll.user32  #user level

user32.ShowWindow(kernel32.GetConsoleWindow(), True) #showing console.. for now

key_pressed = user32.GetAsyncKeyState
#ctypes.windll.user32.GetKeyState?

while True:
  # these ctypes functions are very low level (e.g. SHORT INT / 2 bytes)
    
  print(key_pressed(65)) #this isnt great.
  # returns 32769 data type SHORT when 'A' is pressed -
  # it is only the last "bit" (when converted) that tells us
  # if A is pressed. odd = pressed, even = not pressed.
  # we can use a bitwise operator '& 1' to mask this:
    
  print( key_pressed(65) & 1 ) #1 if pressed, 0 if not.