SendKeys: data exchange via Clipboard between Calc and Notepad

The following sample demonstrates the power of the WSHSendKeys method. The sample launches Calc and Notepad. Then the expression 10 + 2 is evaluated using Calc. Afterward the result is transfered to the editor's window using the Windows clipboard. At least the script writes several text lines into the editor window. After processing this task, the script closes the calculator window. A typical sample which requires many features not available from WSH for default - but with the WSHExtend ActiveX control the solution is only a few lines of code away. To allow you to study the details I like to discuss the sample step-by-step.

Note: I wrote this sample shortly after WSH 1 release. WSH doesn't provide nothing to simulate keystrokes. Therefore I implemented the WSHSendKeys method in WSHExtend because I needed a tool in WSH 1 to control applications like Notepad which doesn't offer an automation interface. WSHSendKeys offers you the ability to simulate nearly any user interaction with an application (excluding mouse clicks and print screen). Since WSH 2 was released (in February 2000) the WSHSendKeys method became obsolete. I recommend to use also the SendKeys method provided from the WSHShell object. This method has a similar interface as WSHSendKeys.

Set oWshShell = WScript.CreateObject ("WScript.Shell")
oWshShell.SendKeys "Hello, world"

The second line send the string "Hello, world" to the window that has the focus. Keep in mind that both methods paste the strings into the Windows message buffer, and Windows allows the application that has the focus to read from that message buffer. This is also the reason why SendKeys doesn't work with Command Prompt window application (DOS-Commands).

The sample (which is implemented in JScript) launches the two applications Calc and Notepad using the following commands:

var Wsh = WScript.CreateObject("WSHExtend.WinExt"); // retrieve object reference
var ProcID_Calc = Wsh.WSHShell ("Calc.exe",1);      // launch Windows calculator
var ProcID_NotePad = Wsh.WSHShell ("Notepad.exe",1);// launch Windows editor

I have used the WSHShell method from the WSHExtend ActiveX control (instead of the Run method provided from the WSH), because this method returns a process ID, which may be used later on to access the application's window. The second parameter of the WSHShell method sets the window mode to normal.

Now the expression 10 + 2 shall be evaluated using the Windows calculator. This may be done using the WSHShell method. But before we can apply this method, a few things should be arranged. The WSHSendKeys method allows you to send any keystroke to the application window. But this is the window which has currently the focus. Executing the commands given above causes the situation that the editor window probably got the focus. But we can't be sure. After executing the WSHShell method to launch an application, Windows need some time to load the exe program and show the application window. In most cases, if a script deals only with one application, I use the WSHWait method to suspend the script for a few seconds (in WSH 2 you should use the Sleep method to suspend a script). This assures Windows the time to launch the application.

In the sample here there is a second problem: we have to deal with two application windows. The sequence shown above launches the Windows editor (which delays the script and probably gives Windows enough time to launch Calc). Therefore I omitted the WSHWait call, but we need to set the focus to the Calc window to evaluate the expression. This task may be done using the WSHAppActivate method also provided by WSHExtend. The following code assures that Calc receives the focus:

// set focus to the calculator window and check
// whether the activation is succesful
var status = Wsh.WSHAppActivate (ProcID_Calc); 
if (status != 0)
 { // a run-time error code occurs
 WScript.Echo ("Error: Can't activate Calc",
 "Error number ", status);
 WScript.Quit();
 }

WSHAppActivate requests the process-ID value returned from WSHShell to set the application into the foreground and set the focus to the application window. This method returns also a status code which may be checked for success or failure. If this test is successful, we are ready to use WSHSendKeys to send the expression to Calc.

// just calculate 10 + 2 = 
Wsh.WSHSendKeys ("10", true);
Wsh.WSHSendKeys ("{+}", true);
Wsh.WSHSendKeys ("2", true);
Wsh.WSHSendKeys ("=", true);

You can use also the following code to use WSH 2 Sendkeys method:

var Wsh = WScript.CreateObject ("WScript.Shell");
// just calculate 10 + 2 =
Wsh.SendKeys ("10");
Wsh.SendKeys ("{+}");
Wsh.SendKeys ("2");
Wsh.SendKeys ("=");

The WSHSendKeys method requests the keycode as a first parameter. The second parameter is set to true to let the method return immediately. (The WSH 2 SendKeys method uses only one parameter.) The + character within the expression must be enclosed in curley braces, because the + sign is used as an escape character within WSHSendKeys (and also within SendKeys). The curley braces causes the method to pass the + sign to the application (see also the WSHSendKeys description in this site, which may be used also for SendKeys).

OK, that's fine, but how to get the result into the Editor window? No problem! We don't need something like a WSHClipBoard method, it is sufficient to send a few simple keystrokes: Strg+C to copy the result from the calculator to the clipboard, and Strg+V to insert the clipbord content into the Editor window. This is done using the following statements:

Wsh.WSHSendKeys ("^{c}", true); // result into clipboard
var status = Wsh.WSHAppActivate (ProcID_NotePad);
.... 
// write text into the editor window
// first insert result from the clipboard
Wsh.WSHSendKeys ("Calculation Result: ", true);

After these steps the script continues to write some text into the editor window using commands like:

Wsh.WSHSendKeys (" Hello, World\n", true);

The "\n" characters stands for the escape character to force a line feed. After setting the focus again to the calculator the next line simulates a Alt+F4 shortcut which closes the Calc window.

Wsh.WSHSendKeys ("%{F4}", true); // close calc with Alt+F4

The details may be obtained from the following listing.

//************************************************
// File:     SendKeys1.js (WSH sample in JScript)   
// Author:   (c) G. Born
//
// Demonstrates the use of the WSHSendKeys method
// and the use of the Shell and AppActivate methods.
// Launches Calc and Notepad and write into the application
// windows.
// Attention: The script requires the ActiveX control
//            WSHExtend !!! 
//
// In no way shall the author be liable for any
// losses or damages resulting from the use of this
// program. Use AS-IS at your own risk.
//
// The code is the property of the author. You may
// use the code and modify it, as far as this header
// remains intact. Further updates and other samples
// may be found on my site:
// http://www.borncity.de
//************************************************

// Create the WSHExt object to extend the WSH
// with the WSHShell method.

var Wsh = WScript.CreateObject("WSHExtend.WinExt");

// launch Windows calculator

var ProcID_Calc = Wsh.WSHShell ("Calc.exe",1);

// launch Windows editor

var ProcID_NotePad = Wsh.WSHShell ("Notepad.exe",1);

// set focus to the calculator window and check
// whether the activation is succesful
var status = Wsh.WSHAppActivate (ProcID_Calc); 
if (status != 0)
 { // a run-time error code occurs
    WScript.Echo ("Error: Can't activate Calc",
                  "Error number ", status);
    WScript.Quit();
 }

// just calculate something
Wsh.WSHSendKeys ("10", true);
Wsh.WSHSendKeys ("{+}", true);
Wsh.WSHSendKeys ("2", true);
Wsh.WSHSendKeys ("=", true);

// result into clipboard
Wsh.WSHSendKeys ("^{c}", true);

WScript.Echo ("Close calculator, write text into editor window.");

// set focus to the editor window and check
// whether the activation is succesful

var status = Wsh.WSHAppActivate (ProcID_NotePad); 
if (status != 0)
 { // a run-time error code occurs
    WScript.Echo ("Error: Can't activate NotePad",
                  "Error number ", status);
    WScript.Quit();
 }

// write text into the editor window
// first insert result from the clipboard
Wsh.WSHSendKeys ("Calculation Result: ", true);
Wsh.WSHSendKeys ("^{v}", true);
Wsh.WSHSendKeys ("\n\n", true);

// Now write the text 30 times
for (var i = 1; i <=30; i++)
 {
  Wsh.WSHSendKeys (i + " Hello, World\n", true);
 }

// set focus to calc and check
// whether the activation is succesful

var status = Wsh.WSHAppActivate (ProcID_Calc); 
if (status != 0)
 { // a run-time error code occurs
    WScript.Echo ("Error: Can't activate Calc",
                  "Error number ", status);
    WScript.Quit();
 }

// close calc with Alt+F4
 Wsh.WSHSendKeys ("%{F4}", true);  
// End

Because WSH 2 is now available on most Windows systems I recommend using the SendKeys method:

var oWshShell= WScript.CreateObject("WScript.Shell");
// Now send some code to the window that has the focus
oWshShell.SendKeys ("Hello, world"");
oWshShell.SendKeys ("10");
Wsh.WSHSendKeys ("{+}");
Wsh.WSHSendKeys ("2");
Wsh.WSHSendKeys ("=");

I was realy impressed after I recognized how easy it may be to control Windows applications using the WSHSendKeys or the SendKeys method (and the other methods). This methods bring WSH close to something like a "programmable macro player". I wrote scripts to create a new user under Windows 98. You can use the methods also to invoke a property page and set system or application properties and more. Additional information about this sample (the sample in VBSrcipt) and more may be found in my WSH books.

Back

(c) G. Born