Sidharth Ghoshal
Sidharth Ghoshal

Reputation: 720

How to simulate string keyboard input using Python?

I'm using windows 8 and have the windows api module

I am trying to create a method:

TypeInput(argument) #argument is a string

with the objective that my method simulates the typing of the argument if the argument is a string.

Unfortunately,

I currently simulate typing using:

win32api.keybd_event(win32con.KEYCODE, MS KEYCODE, 0, 0)

And i don't know how to abstract this so that I can plug in arbitrary characters.

My initial guess was to do unicode conversions

but it seems the problem is worse for example

ord('f') = 102 = 66 in hex

but the Windows code for 'f' is

0x046

and 46 isn't 66...

so i'm not really sure how they are converting, It doesn't seem to be equally spaced.

At this point i have come to the conclusion there is a more elegant way to do it.

Would someone be so awesome as to show me it and explain?

Upvotes: 0

Views: 1755

Answers (1)

Eric Brown
Eric Brown

Reputation: 13932

You want to use SendInput, rather than keybd_event, and make sure that the KEYBDINPUT.dwFlags field has the KEYEVENTF_UNICODE flag set. If you're not using KEYEVENTF_UNICODE, then you have to make sure to set both the scan code and the key code; otherwise you will get app-specific failures.

There is a Python wrapper for SendInput, so that will help too.

Upvotes: 2

Related Questions