-1

I want to send a keyboard keystroke to active window, for example key A or Backspace using python. How can I do this?

I know active window coordinates as well (if it can help).

  • Hello and welcome to StackOverflow. Please take some time to read the help page, especially the [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922) and the [ask] section. – Peter Tutervai Aug 04 '17 at 23:06

1 Answers1

-2

The Windows API method to do this is SendInput which is part of the User32 library. It sends keyboard and mouse input to the foreground/active window. SendInput uses the INPUT structure, specifically called KEYBDINPUT. It has the option of sending more than one INPUT because the first parameter details that:

nInputs [in]

Type: UINT
The number of structures in the pInputs array.

An example of using SendInput in Python is specified in the answer on this question.

You use the MapVirtualKey function to map a virtual key code to a scan code

Jason
  • 150
  • 1
  • 10
  • 1
    [You can’t simulate keyboard input with (Post|Send)Message](https://blogs.msdn.microsoft.com/oldnewthing/20050530-11/?p=35513) – Remy Lebeau Aug 05 '17 at 01:07
  • 1
    **SendInput** - yet, correct answer. **SendMessage** shouldn't really be discussed, unless it's in the context of sending a WM_CHAR or WM_KEYDOWN/WM_KEYUP message to a window. But those types of hacks just cause more trouble... since not all windows respondto input the same way. I'd recommend adjusting your answer to just speak of the SendInput function. – selbie Aug 05 '17 at 02:02