Friday, September 30, 2011

Sendkeys

Sendkeys

Many applications, such as Excel and Word, provide their own built-in core object model. WSH scripts can interact directly with these applications by first instantiating references to the application’s objects and then accessing their methods and properties. The only trick here is that you need to know the objects that make up the application’s object model, as well as their associated methods and properties. You can often get this information from the application vendor’s Web site or from searching the Internet. Of course, if the application that you want to work with does not expose an object model for your scripts to work with, you can always try using the SendKeys() method.

[Book named "Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition" has "A Quick Overview of the WshShell SendKeys() Method" on pg 89.]

Sendkeys method sends keystrokes to the active window.

object.Sendkeys(string)

where object is WshShell object and string is keystroke or keystrokes you want to send.

Example 1 of Sendkeys: Writing on Notepad

set objSendKey=CreateObject("WScript.shell")
set objSetFocus = Window("nativeclass:=Notepad","index:=0")

SystemUtil.Run "notepad.exe", "", "", ""
wait 2
objSetFocus.Move 10,10
wait 1
objSetFocus.Click
objSendKey.SendKeys("QTP")

Example 2 of Sendkeys: Using Calculator

set objSendKey=CreateObject("WScript.shell")
set objSetFocus = Window("nativeclass:=Notepad","index:=0")

objSendKey.Run "calc"

objSendKey.AppActivate "Calculator"
wait (3)
objSendKey.SendKeys "1{+}"
wait (3)
objSendKey.SendKeys "2"
wait (3)
objSendKey.SendKeys "="

Example 3 of Sendkeys: Pressing Enter

set objSendKey=CreateObject("WScript.shell")
set objSetFocus = Window("nativeclass:=Notepad","index:=0")

SystemUtil.Run "notepad.exe", "", "", ""
wait 2
objSetFocus.Move 10,10
wait 1
objSetFocus.Click
objSendKey.SendKeys("Foo bar")
objSendKey.SendKeys "{ENTER}"

Example 4 of Sendkeys: Using DOS Prompt

Set objSendKey=CreateObject("WScript.shell")

objSendKey.Run "cmd"

objSendKey.AppActivate "cmd"
wait (3)
objSendKey.SendKeys "dir"
wait (3)
objSendKey.SendKeys "{ENTER}"
wait (3)

Example 5 of Sendkeys: Another use of Sendkeys
Taking Screenshots

More on SendKeys
SendKeys Method MSDN
VBScript SendKeys
SendKeys
Does or Can VBscript's SendKeys support Unicode?
Another example of Sendkeys with Outlook
WshShell.SendKeys