March 27, 2012

Sending Keys to Invisible or Unfocused Windows

Filed under: Automation,Scripting — Marcus Tettmar @ 2:32 pm

Can you send keystrokes to invisible or unfocused windows? The answer is yes, if the control you want to send the keystrokes into is a “windowed control”. That is, one that has a handle.

If that’s too technical just try using the “Send Keys to Object Wizard” in Macro Scheduler 13 which generates code that uses the ObjectSendKeys function. Or Watch the video to see it in action.

If the wizard is able to identify the control the code that it generates will work even if the window is not visible or not focused. This is because it works by sending the keyboard codes directly to the specified control.

In contrast the regular Send command sends characters into the global input buffer. In other words it sends keystrokes into whatever happens to have the focus at the time. The great thing about this is that it means it can send keystrokes to ANY thing regardless of whether it is a windowed control or not and regardless of the technology. But the control does need to be focused.

So if your control has a handle then you can use ObjectSendKeys to send keystrokes to it and avoid it having to be focused. This also means it will work even if the window is minimized, or hidden. This could be turned to your advantage if you wanted to manipulate a window and be able to do something else at the same time. Of course this assumes that all the controls have a handle which is not always the case.

As an example, run this script. Notepad will open, then be minimized and then text will be sent into it. When the script has finished restore Notepad and you should see the text inside it.

Run>Notepad.exe
WaitWindowOpen>Untitled - Notepad
WindowAction>2,Untitled - Notepad

GetWindowHandle>Untitled - Notepad,hWndParent
FindObject>hWndParent,Edit,,1,hWnd,X1,Y1,X2,Y2,result
ObjectSendKeys>hWnd,{"Hello World"}