Search code examples
pythonkeypress

Key Presses in Python


Is it possible to make it appear to a system that a key was pressed, for example I need to make A key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.

A better way to put it, I need to emulate a key press, I.E. not capture a key press.

More Info (as requested): I am running windows XP and need to send the keys to another application.


Solution

  • 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}")