0

I am creating a program that needs to be able to detect keyboard presses outside of the window. How would I be able to do something like the following:

while True:
    if getKey() == w:
        #Do a thing
    if getKey() == a:
        #Do a different thing
martineau
  • 119,623
  • 25
  • 170
  • 301
bengdahl
  • 13
  • 2
  • 5

1 Answers1

0

Assuming "outside of the window" actually means "outside of the console" you could try something like the following to append your keyword events to an output file.

import win32api 
import sys
import pythoncom, pyHook

buffer = ''
def OnKeyboardEvent(event):
if event.Ascii == 5: 
  sys.exit() 
if event.Ascii != 0 or 8: 
  f = open ('c:\\output.txt', 'a') 
  keylogs = chr(event.Ascii) 
if event.Ascii == 13: 
  keylogs = keylogs + '\n' 
  f.write(keylogs) 
  f.close() 
while True:
  hm = pyHook.HookManager() 
  hm.KeyDown = OnKeyboardEvent 
  hm.HookKeyboard() 
  pythoncom.PumpMessages()

http://antihackingtutorials.blogspot.de/2012/06/in-this-tutorial-we-will-show-you-how.html

Philipp Braun
  • 1,583
  • 2
  • 25
  • 41