April 17, 2013

Paste Into Object Without Using Keystrokes

Filed under: Automation,Scripting — Marcus Tettmar @ 11:03 am

Someone asked today how it might be possible to paste what is in the clipboard into an object using Macro Scheduler without having to use keystrokes.

It can be done by sending the WM_PASTE message using the SendMessage API function.

Here’s an example:

//Sending WM_PASTE to an object causes a clipboard paste, like sending CTRL-V

//constants - here we define the WM_PASTE constant
Let>WM_PASTE=770

//we need the handle of the object we want to send WM_PASTE to - 
// - as an example let's find the handle of Notepad's edit window
// - for this example make sure Notepad is running with empty document
// - so that the window title us "Untitled - Notepad".  Modify if needed

GetWindowHandle>Untitled - Notepad,hWndParent
FindObject>hWndParent,Edit,,1,hWnd,X1,Y1,X2,Y2,result

//now send WM_PASTE to it using SendMessage API
LibFunc>User32,SendMessageA,result,hWnd,WM_PASTE,0,0

The only benefit I can see with this is that it doesn’t require keyboard focus. In theory neither should ObjectSendKeys and a CTRL-V require keyboard focus. The latter is simpler so I’d tend towards using that. And there may be some applications that work at a higher level and actually expect to see CTRL-V or similar.

Never-the-less it’s a nice example of sending a Windows message and it may be useful for some. So here it is.