[Previous] [Table of Contents] [Next]

Using the SendKeys Method to Simulate Keystrokes

A script can invoke an application and switch its window to the foreground. All keystrokes that the user enters affect that application window. Sometimes a script needs the ability to mimic user input.

Using SendKeys in WSH 2

In WSH 2, you can use the SendKeys method of the WshShell object. Let's look at a simple example. The following JScript code uses the Run method to launch Calculator:

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run("Calc.exe");
WScript.Sleep(200);

The last statement is required to allow the Calculator window to receive the focus. If this delay is omitted, the script might execute subsequent statements that send keystrokes before Calculator receives the focus; if this happens, all keystrokes will be lost.

After Calculator becomes active, the script sends the expression 10 + 2 = to the Calculator window. The SendKeys method has the following syntax:

 WshShell.SendKeys keys

The SendKeys method is part of the WshShell object; the keys parameter contains the character or characters to send. Each "key" submitted in this parameter is represented by at least one character. Keyboard keys can be represented by a single character. For example, to send the A key, you pass the character A in the key argument. If the string contains several characters (such as ABC), the characters are sent to the application.

The plus sign (+) has a special meaning in the SendKeys command. (See Table 13-2.) This character must be enclosed within braces in order to be passed to the method. To send a plus sign, for example, you write the string within the key parameter as {+}.

Thus, you use the following statements to send the commands to the Calculator window:

WshShell.SendKeys("10");
WshShell.SendKeys("{+}");
WshShell.SendKeys("2");
WshShell.SendKeys("=");

Each SendKeys call submits a parameter that contains the string. Calculator evaluates the expression and displays the value 12. The following commands pause the script and clear the result in Calculator's display:

WScript.Sleep(2000);
WshShell.SendKeys("c");

Within a loop, the script forces Calculator to add the numbers 1 through 3:

for (var i = 1; i <= 3; i++)
{
    WshShell.SendKeys(i); // Add numbers 1 through 3.
    WshShell.SendKeys("{+}");
}

The full script sample is shown in Listing 13-4.

Listing 13-4 SendKeysWSH2.js

//*****************************************************
// File:     SendKeysWSH2.js (WSH 2 sample in JScript)
// Author:   (c) G. Born
// 
// Using the SendKeys method to launch Calculator 
// and make a calculation
//*****************************************************

// Create WshShell object, which the Run method requires.
var WshShell = WScript.CreateObject("WScript.Shell");

// Launch Calculator.
WshShell.Run("Calc.exe");

// Pause until Calculator is ready to receive input;
// otherwise, the "keyboard input" from SendKeys will go
// into the Windows message buffer and will be passed to
// the active window before Calculator gets the focus. 
WScript.Sleep(200);          // Just wait a little while.

WshShell.SendKeys("10");
WshShell.SendKeys("{+}");
WshShell.SendKeys("2");
WshShell.SendKeys("=");

WScript.Sleep(2000);        // Wait two seconds.
WshShell.SendKeys("c");     // Clear result.

for (var i = 1; i <= 3; i++)
{
    WshShell.SendKeys(i);    // Add numbers 1 through 3.
    WshShell.SendKeys("{+}");
}

WScript.Echo("Terminate?");
WScript.Sleep(200);
WshShell.SendKeys("%{F4}");  // Close Calculator using Alt+F4.
 
//*** End

More on the SendKeys method

The plus sign (+), the caret (^), the percent sign (%), the tilde (~), and parentheses ( ) have special meanings in the SendKeys command. (See Tables 13-1 and 13-2.) These characters must be enclosed within braces for the string to be passed to the method. To send a plus sign, for example, you write the string within the key parameter as {+}. Brackets ([ and ]) must also be enclosed within braces before they're passed to the SendKeys method because these characters have a special meaning in applications that use Dynamic Data Exchange (DDE). You send the characters for braces as {{} and {}}.

Some keys on your keyboard, including the Enter key and the Tab key, don't produce visible characters. To pass these keys to the SendKeys method, you must code them. Table 13-1 shows the coding of all the special keys.

Table 13-1 Codes for Special Keys in the SendKeys Method

Key Code
Backspace {BACKSPACE}, {BS}, or {BKSP}
Break {BREAK}
Caps Lock {CAPSLOCK}
Delete {DELETE} or {DEL}
Cursor down {DOWN}
End {END}
Enter {ENTER} or ~
Esc {ESC}
Help {HELP}
Home {HOME}
Insert {INSERT} or {INS}
Cursor left {LEFT}
Num Lock {NUMLOCK}
Page Down {PGDN}
Page Up {PGUP}
Print {PRTSC}
Cursor right {RIGHT}
Scroll lock {SCROLLLOCK}
Tab {TAB}
Cursor up {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}

To send key combinations that include Shift, Ctrl, or Alt, you must insert a special code in front of the second key code. The special codes for these keys are shown in Table 13-2.

Table 13-2 Codes for Key Combinations in the SendKeys Method

Key Code Used in Front of Second Key Code
Shift +
Ctrl ^
Alt %

Consequently, ^X stands for Ctrl+X. If a key combination contains more than two keys, you must place the characters within parentheses. This arrangement might sound complicated, but it's not. For example, to send the key combination Shift+E+C, you send the string +(EC). The plus sign represents the Shift key, and (EC) represents the keys E and C, which must both be pressed while the Shift key is held down. To send a key combination of Shift+E followed by the C key, you use the string +EC instead. The plus sign represents the Shift key, which is used in combination with E. After that key combination is processed, the single character C is received. The parentheses in the first example force Windows to interpret the keys within the braces as a key combination with the leading control code for Shift.

To represent a repeating key, you use the format {keycode number}. (The blank between keycode and number is mandatory.) For example, the string {LEFT 42} represents 42 presses of the Cursor left key; the string {H 10} represents 10 presses of the H key.

TIP
To toggle the Num Lock key automatically, you can write a script that sends the code {NUMLOCK} using SendKeys. Executing this script from the Startup menu toggles the Num Lock key during each system start. The NumLock.vbs file in the \WSHDevGuide\Chapter13 folder on the companion CD does this for you.

Manipulating Two Applications Using SendKeys

Now I'll show you a sample that uses the SendKeys method and then show you how to use SendKeys in combination with other methods. The sample is written in JScript and launches Calculator and Notepad with the following commands:

oWSH.Run("Notepad.exe", 1);  // Launch Notepad with empty window.
WScript.Sleep(500);          // Delay until Notepad gets the focus.
oWSH.Run("Calc.exe", 1);     // Launch Calculator with empty window.
WScript.Sleep(500);          // Delay until Calculator gets the focus.

The Sleep method ensures that Calculator receives the focus. You can then use SendKeys to calculate 10 + 2 using the following commands:

oWSH.SendKeys("10");         // Just calculate something.
oWSH.SendKeys("{+}");
oWSH.SendKeys("2");
oWSH.SendKeys("=");

The sequence above uses the key codes to force Calculator to evaluate the expression. You can then use the following statement to copy the result to the Clipboard:

oWSH.SendKeys("^{c}");      // Copy result to Clipboard.

The code ^{c} represents the Ctrl+C shortcut. The script then displays a dialog box that informs the user that the result will be written to the Notepad window. If the user closes the dialog box, the script transfers the focus to the Notepad window and inserts the Clipboard content by using the following code:

oWSH.AppActivate(Edit_Title);
// Write text to Notepad window.
// First insert result from the Clipboard.
oWSH.SendKeys("Calculation Result: ");
oWSH.SendKeys("^{v}");
oWSH.SendKeys("\n\n");

The first statement uses the window title to transfer the focus to the application. (This approach isn't reliable if more than one open window uses the same title.) The three calls to the SendKeys method write some text into the Notepad window and then paste the calculation result from the Clipboard. The code \n\n creates two new lines at the end of the document. The script then uses a simple for loop to write more text to the Notepad window:

// Now write the text 30 times.
for (var i = 1; i <= 30; i++)  
{
    oWSH.SendKeys(i + " Hello, world\n");
}

The script then tries to close the Calculator window and the Notepad window. It first tries to close the Calculator window:

oWSH.AppActivate(Calc_Title); // Set focus to Calculator.
oWSH.SendKeys("%{F4}");       // Close Calculator using Alt+F4.

Using Alt+F4 to close the Notepad window invokes the "Do you want to save the changes?" dialog box, so the script also needs an additional step to "click" the No button.

oWSH.AppActivate(Edit_Title); 
oWSH.SendKeys("%{F4}");  // Close Notepad using Alt+F4.
oWSH.SendKeys("%{N}");   // "Click" the No button.

The full implementation is shown in Listing 13-5.

Listing 13-5 SendKeys1.js

//**************************************************
// File:     SendKeys1.js (WSH 2 sample in JScript)   
// Author:   (c) G. Born
//
// Using the SendKeys method and the AppActivate 
// method to launch Calculator and Notepad and 
// write to the application windows
//**************************************************

// Define the title strings of the application windows.
// Important: Strings depend on the localized version of Windows.
var Edit_Title = "Untitled - Notepad";   // Window title
var Calc_Title = "Calculator";           // Window title

// Create the WshShell object, which Run and 
// AppActivate require.
var oWSH = WScript.CreateObject("WScript.Shell");

// Try to launch two applications. To ensure that the
// last application receives the focus, delay the script.
oWSH.Run("Notepad.exe",1);  // Launch Notepad with empty window.
WScript.Sleep(500);         // Delay until Notepad gets the focus.
oWSH.Run("Calc.exe",1);     // Launch Calculator.
WScript.Sleep(500);         // Delay until Calculator gets the focus.

oWSH.SendKeys("10");        // Just calculate something.
oWSH.SendKeys("{+}");
oWSH.SendKeys("2");
oWSH.SendKeys("=");

oWSH.SendKeys("^{c}");      // Copy result to Clipboard.

WScript.Echo("Write text to Notepad window.");

// Set focus to Notepad window.
oWSH.AppActivate(Edit_Title); 
// Write text to Notepad window.
// First insert result from Clipboard.
oWSH.SendKeys("Calculation Result: ");
oWSH.SendKeys("^{v}");
oWSH.SendKeys("\n\n");

// Now write the text 30 times.
for (var i = 1; i <= 30; i++)
{
    oWSH.SendKeys(i + " Hello, world\n");
}

WScript.Echo("Close Calculator window.");

oWSH.AppActivate(Calc_Title); // Set focus to Calculator.
oWSH.SendKeys("%{F4}");       // Close Calculator using Alt+F4.

WScript.Echo("Close Notepad window.");

// Set focus to Notepad and send terminate command.
oWSH.AppActivate(Edit_Title); 

oWSH.SendKeys("%{F4}");  // Close Notepad using Alt+F4.
oWSH.SendKeys("%{N}");   // "Click" the No button.
 
//*** End

You now know a few WSH 2 programming techniques for controlling external applications. For a much deeper discussion and information on additional methods for handling external applications, see Advanced Development with Microsoft Windows Script Host 2.0.