8

Extremely straightforward question.

Just want to press a keyboard key. Like enter, using pywin auto. I don't want to press it in the context of any application window.

Just a raw keypress of a keyboard key, like a or enter or backspace.

Hangfish
  • 346
  • 2
  • 5
  • 13

3 Answers3

6

Just use

# from pywinauto.SendKeysCtypes import SendKeys # old for pywinauto==0.5.x
from pywinauto.keyboard import send_keys

send_keys('some text{ENTER 2}some more textt{BACKSPACE}', with_spaces=True)

Docs: https://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html

P.S. SendKeysCtypes was renamed to keyboard in pywinauto 0.6.0+.

Vasily Ryabov
  • 9,386
  • 6
  • 25
  • 78
  • Thank you, the **"{ENTER}"** functionality worked. How broadly is this supported? Can I have all the modifier keystrokes to do this? Like Alt, Ctrl Tab. Also can I make combinations in sendkeysCtypes? Like "Ctrl + 1 or Ctrl + C`" – Hangfish Oct 27 '16 at 08:52
  • 1
    It's possible. I've just described it in the new docs for renamed keyboard module (other things are unchanged): http://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html – Vasily Ryabov Oct 27 '16 at 20:05
  • latest documentation: http://pywinauto.readthedocs.io/en/latest/code/pywinauto.keyboard.html?highlight=SendKeys – JinSnow Jan 25 '17 at 20:01
  • @VasilyRyabov running this (only) `pywinauto.keyboard import SendKeys SendKeys('^a^x')` only send `^A^X` to the python console. (It doesn't select all/copy text on the active windows). Any idea how to makes it work? – JinSnow Jan 25 '17 at 20:27
  • Console is not a GUI application. Just try to press the same keys manually. It will print the same symbols. :) – Vasily Ryabov Jan 26 '17 at 12:42
  • If you want to capture stdout of the command line process you spawned, it's better to use standard module `subprocess`. – Vasily Ryabov Jan 26 '17 at 12:44
  • I've just used `from pywinauto.SendKeysCtypes import SendKeys` (as in your answer) and received 'ImportError: No module named 'pywinauto.SendKeysCtypes''. Please, what should we be using now? – Bill Bell Sep 20 '17 at 21:46
  • Currently it should be `from pywinauto.keyboard import SendKeys` and it's mentioned in the answer. – Vasily Ryabov Sep 21 '17 at 07:27
2

I had to change the include to get the code working:

from pywinauto.keyboard import send_keys, KeySequenceError

send_keys('some text{ENTER 2}some more textt{BACKSPACE}', with_spaces=True)
Vasily Ryabov
  • 9,386
  • 6
  • 25
  • 78
Olc
  • 69
  • 4
0

I got this running for my game, and it works on notepad.exe too

from pywinauto import Application

app = Application(backend="win32").connect(path="Mario")
# app.MarioClass.minimize() # if you want to minimized
app.MarioClass.send_keystrokes('Hi {ENTER}')
DagicCross
  • 401
  • 3
  • 13