Home Page

 


EARLIER FEATURES

 


FEATURES CONTENTS

 


LATER FEATURES

 

Features Contents


16th March 2003

KEYBOARD MACROS
WITH
WINDOWS SCRIPTING HOST

Brian Grainger

email.gif (183 bytes)
brian@grainger1.freeserve.co.uk


 

INTRODUCTION

Users of Windows 98 or later who peruse the list of .exe files in the Windows directory will have noticed wscript.exe and cscript.exe and, perhaps, wondered what they do. They are connected with a Windows tool called Windows Scripting Host. This article will describe the background to Windows Scripting Host (WSH), a little bit about basic Object Oriented Programming(OOP) and how to do OOP with WSH to create keyboard macros.

WHAT IS WINDOWS SCRIPTING HOST?

I have mentioned in the past that there are hidden tools in Windows, some of which can be very useful if Microsoft would only tell us they were there! WSH is one of these tools and it turns out to be very useful indeed. During my meanderings through the Internet I had come across WSH before but its usefulness did not strike me until I read a book. I am indebted to ‘VBScript in a Nutshell’, published by O’Reilly, for really stirring my interest. While the book was about VBscript, it included one chapter on WSH.

WSH was first introduced into Windows with Windows 98. Its functions were more limited than those it has today. In keeping with most Microsoft products it gets released and then is developed as time goes on. In the case of WSH it has developed more dramatically than is usual.

Back in the days of DOS you could create batch files to execute a set of commands automatically. When Windows appeared on the scene there was no real equivalent in the Windows environment, although sometimes it was still possible to revert to the DOS prompt and execute a batch file. Doing something like opening File Manager, moving to Directory ABC and renaming all *.def files to *.ghi was not possible.

Windows Recorder

The first primitive attempt at a Windows batch language was ‘Recorder’ that came with Windows 3.x. It was used to record keystrokes and play them back later on demand. This was how keyboard macros were created. Recorder was very useful for this purpose but not as an all purpose Windows batch file creator. Although popular with the advanced user, including me, Windows Recorder never caught on and was dropped in Windows 95. This caused concern amongst the advanced users who had lost the facility, but happily one could simply extract the Windows Recorder executable from Windows 3.1 and use it in Windows 95 without problem.

As I noted earlier, Windows 98 came with WSH 1.0. It provided objects and methods for accessing the file system and registry as well as network resources. Clearly, it was aimed at developers creating installation files and network system administrators who might want to carry out a standard routine on every workstation on the network. The general user was not informed of WSH being part of the package. Since the limited functionality at that time meant that even the routine I will introduce in this article would not work, perhaps it is just as well.

WSH 2.0 was introduced fairly quickly afterwards and was part of NT4. Primarily, this included items on the wish list of WSH 1.0 users. It included 3 new objects and 11 new methods and properties. It also included the capability of integration with XML. By this time WSH was useful for us hobby users as well, but Microsoft still did not tell us about it! Microsoft has communicated totally with the Microsoft Developer Network and no-one else. To be fair, the communications with the Developer network were comprehensive and if you look at the web site, (more of that later), you can get lots of useful information.

At some point later, I am not sure whether with Windows 2000 or XP, the numbering system of WSH versions was changed to 5.x. It is now at version 5.6 and readers are encourage to get this latest version, irrespective of Windows version used.

To sum up, WSH is a tool to execute a scripting language with Windows. It brings the equivalent of a batch language to the Windows environment and, while primarily aimed at developers and network system administrators, it does provide some usefulness to the ordinary user. WSH does NOT provide a full programming environment for application development. That is still the preserve of Visual BASIC, C++, Java, etc. By default WSH will execute Visual Basic Script, (.vbs), Microsoft's equivalent of JavaScript, JScript (.js) and Windows Script Files (.wsf). The latter is the special form that will allow interaction with XML.

GETTING A COPY OF WINDOWS SCRIPTING HOST

The Microsoft centre for all things to do with scripting, including WSH, is at:
http://msdn.microsoft.com/scripting/

You can follow the links from there or go directly to the download page and download WSH 5.6 (scr56en.exe) and the documentation (scrdoc56en.exe). The download page is at:

http://msdn.microsoft.com/library/default.asp?url=/downloads/list/webdev.asp

Other tools are available, such as a means to encode the script file, keeping it hidden from prying eyes, and a tool helpful for debugging a script development. The debugger is included as part of Internet Explorer 5, so you may already have that.

Installation of WSH and its documentation is simplicity itself.

Running the scr56.exe file will add new, or replace earlier versions of, wcsript.exe and cscript.exe files together with some associated .dll files. The changes are made in the Windows and Windows System areas. In addition the registry will be changed to set up file associations between WSH and the following file types:

.js

.vbs

.wsf

.jse

.vbe

.wsh

NO shortcuts will be added to the Desktop or Start button. One does not run WSH by itself.

Running the scrdoc56en.exe file will install the documents. You will be asked for a folder to store them in. ( I chose C:\Program Files\Microsoft Windows Script\ScriptDocs). A single compiled HTML help file is copied to the folder, the registry is altered slightly to say the documents have been installed and a shortcut is added to the Start button Programs list.

YOUR FIRST WSH SCRIPT

Assuming you have installed everything OK, it is time to write and run your first script. By tradition this is a script to display the message 'Hello World'!

Open up your favourite text file editor, Notepad will do, and type the following line:

WScript.Echo "Hello World!"

Now save the file as 'Hello.vbs', (without the quotes).

To run this program you can double click 'Hello.vbs' within My Computer or Windows Explorer, or call it up from the Start button, Run option.

If you want to be really clever go to the command prompt window (MSDOS prompt) and type:

cscript "c:\my documents\windowsscripts\hello.vbs"

In this case the bit between the quotes includes the directory path to the file you have created.

When you choose the Windows method of running Hello.vbs you will see a small window pop up, whose title is Windows Script Host, with the message 'Hello World!' and an OK button inside. Click the OK button to remove the window.

Hello World!

If you choose the command prompt to run the program then the message 'Hello World!' will be output to the command prompt window.

The script that did this magic, the one liner in 'Hello.vbs', is hardly complicated and contradicts what I said in my article about TCL. It IS possible to run Javascript, (or VBScript), outside of a browser. I just did not know about Windows Scripting Host then! However, you still do not have much control over the look of the resulting window, which clarifies the point I made earlier that WSH does NOT provide an environment for full development. You are limited by what scripts can do. Nevertheless, you can do quite a lot with scripts, but in order to do so I need to introduce the concept of Object Oriented Programming (OOP).

OOP AND THE ART OF WINDOWS MAINTENANCE

Graphical user interfaces on computers changed the face of programming, not only outwardly in the display, but also how programming is carried out. Before then everything was procedural based. One line of code was executed after another. Flow control was altered by means of appropriate statements but there was still a flow. GUIs changed all that. A user can click buttons at anytime or in any order! In the old days the results came formatted as the programmer defined. These days the user wants the results in a window which the user can mess with. A new way of programming was devised to deal with this situation, called Object Oriented Programming because it was oriented towards objects!

A window is an object. A button is another object contained by the window object. The whole of the Windows, (or any other GUI), edifice is made up of objects. To program Windows we need to deal with objects. We need to perform actions on them, such as resizing a window or displaying messages in them. In OOP terminology these actions are called methods. Finally these objects have characteristics that describe them. The window object, for example, has a size and position and perhaps a background colour. The size, position, background colour are characteristics of the window. In OOP terminology they are properties. Properties have values that we would like to be able to vary. The final major element to contend with are the external events, such as the click of a mouse button or the passing of the mouse over a particular part of the screen. I am not going to dwell too long on this aspect as our example does not need to consider events. Nevertheless, dealing with events is a vital part of OOP. One other item I am going to ignore in this article is the concept of a class of objects. This is like a general description of an object and within the program one would create an instance of the class to define a particular object.

C64 ROM Routine

The basic building blocks of a program, the objects, are usually defined in the way that Windows is built. In the good old days of PET/Commodore 64 programming we used to interact with the operating system by knowing the in-built ROM routines and how to use them. With Windows we need to know what objects it is made of and what methods and properties can be used with them. This is called the Object Model. The only problem is getting hold of the information from Microsoft! There is a lot of information available but you will need to search out the MSDN area of the web to find it. The help file for WSH also has information but it is more reference manual information than instructions on how to use the object models. I have found the http://www.winscriptingsolutions.com site is also a useful source of information. You can use Google to find others, but you need to know the jargon names of what you are looking for to be successful. For example, I found in my reading that the FileSystemObject object model would be a very useful piece of information. Doing a Google search on FileSystemObject got me what I wanted very quickly. I don't think I would have guessed at that without knowing about it first!

WSH comes with its own small, but very useful, WScript object model, which is described in the documentation. Two of its methods, CreateObject and GetObject, allow WSH to access other object models. This gives the user the opportunity to access many other features than those contained within WScript. However, that is running before we can walk. Our example will stick within the WScript model.

OOP PROGRAMMING WITH VBSCRIPT

Having introduced the terminology it is time for a few guidelines to programming with VBScript.

Any variables used within a program should be explicitly declared, using the Dim statement. If you do not declare them explicitly they are accepted, but there is potential for scripting errors.

A variable has only one data type, variant. It becomes a number, string, Boolean, etc. as required. The programmer need not worry about it.

If you want to use an object you usually have to define it explicitly to get at its methods and properties. Only the top level object of WSH, WScript, is exempt from this rule.

To refer to a method or property of an object one separates the object or method name from the object name by a period.

e.g.

WScript.Echo

refers to the Echo method of the WScript object

 

Wscript.Name

refers to the Name property of the WScript object
(which returns the name of the WSH file, i.e. wscript.exe)

DEFINING A KEYBOARD MACRO WITH WSH

Right at the top I mentioned that the book, ‘VBScript in a Nutshell’, brought my attention to WSH. What really sealed my interest was when I saw it describe the SendKeys method, along with a list of special characters for the function keys. I quite often need a means to automatically send keystrokes repetitively to Excel. This was easy with Lotus 1-2-3 but the VBA programming tool with Excel usually does not cut the mustard. Use of Windows Recorder was my usual way out. With WSH, I now have a way I can use on any modern version of Windows.

Recently, I had another problem that could be solved by a keyboard macro. When a file is copied from the temporary internet file storage area to a standard folder it very often has a sequential number attached.

e.g. Instead of being called index.htm, it will copy to a file called index[1].htm.

Now, if you do a lot of copying then it gets a real pain stripping out these numbers. Nine times out of ten, when the file extension is 3 characters and the sequential number is less than 10, a standard keyboard process can be applied to do the job:-

  • With the filename highlighted in Explorer hit F2 (= rename)
  • Press End
  • Cursor left 4 times
  • Backspace 3 times
  • Press enter
  • Cursor down (optional, but takes you down to the next file so you can start the process again if you have a long list of files to do)

Note that I have defined the whole process by using the keyboard, NOT menu items. This is necessary for the creation of a keyboard macro. It does not mean you cannot use menu items, but you must define the key presses you use to access them.

I now know what keys I need to send to solve my problem, so I can use the SendKeys method to send them.

I also need to define which application, out of the many I may have open at the time, is to receive the keys. Fortunately, the WSH documentation tells me there is a method, AppActivate, to do this.

All I need to do now is write the script.

EXAMPLE SCRIPT AND EXPLANATION

SendKeys and AppActivate are methods of the same object, the WshShell object. This is a child object of the WScript object so I need to instantiate it by using WScript's CreateObject method.

Bearing the above in mind, I can write the script, in VBScript, as follows:

Dim Wsh
Set Wsh = Wscript.CreateObject("Wscript.Shell")
Wsh.AppActivate "Exploring"
Wsh.SendKeys "{F2}{END}{LEFT}{LEFT}{LEFT}{LEFT}{BS}{BS}{BS}~{DOWN}"

I shall explain this line by line.

Dim Wsh

When I instantiate the WshShell object I need to be able to refer to it in some way. Wsh is a variable for this purpose so, first of all, I explicitly declare it with the Dim statement

Set Wsh = Wscript.CreateObject("Wscript.Shell")

This is where I make an instance of the WshShell object.

Note that, as I am using the CreateObject method of WScript, I use the dot notation Wscript.CreateObject to call the method. The bit in brackets is what is called the 'programmatic identifier' of the object to be created and its value is in the documentation! The created object is then assigned to wsh so I can refer to it.

Wsh.AppActivate "Exploring"

Having set everything up this is the first line of real coding. It uses the AppActivate method of the newly defined WshShell object to tell the computer which window is to be activated for subsequent operations. (Which window is given focus is the techie way of saying this!). The string value, "Exploring" in this example, says activate the windows whose title begins with 'Exploring'. On my version of Windows at least, that means a Windows Explorer window. Note that if two Windows Explorer windows were open this code may activate the wrong one. I have not found this to be a problem in the way I use the code as a keyboard macro, since the Explorer window I wish to use has focus already.

Wsh.SendKeys "{F2}{END}{LEFT}{LEFT}{LEFT}{LEFT}{BS}{BS}{BS}~{DOWN}"

This uses the SendKeys method of the created WshShell object to send the keys to the Explorer window. The bits in quotes are the keys to send. Standard alphanumeric keys are simply typed as is. Special code strings, usually in braces, are used to define function keys. The keys in the line above correspond with the keyboard process defined in the previous section. Here is a full list of code strings taken from the documentation for SendKeys. Note that there does NOT appear to be a way of sending the special keys on a Windows keyboard.

Key

Code String

BACKSPACE

{BACKSPACE}, {BS}, or {BKSP}

BREAK

{BREAK}

CAPS LOCK

{CAPSLOCK}

DEL or DELETE

{DELETE} or {DEL}

DOWN ARROW

{DOWN}

END

{END}

ENTER

{ENTER} or ~

ESC

{ESC}

HELP

{HELP}

HOME

{HOME}

INS or INSERT

{INSERT} or {INS}

LEFT ARROW

{LEFT}

NUM LOCK

{NUMLOCK}

PAGE DOWN

{PGDN}

PAGE UP

{PGUP}

PRINT SCREEN

{PRTSC}

RIGHT ARROW

{RIGHT}

SCROLL LOCK

{SCROLLLOCK}

TAB

{TAB}

UP ARROW

{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}

The documentation also tells you how to send the Ctrl and Alt keys in combination with alphanumeric keys.

Having created the script with Notepad, or whatever, save it to a VBScript file, (a file which has a .vbs extension). For the purpose of this example I will assume it is saved to:

C:\My Documents\WindowsScripts\Remove(n).vbs

CONVERTING THE SCRIPT TO A KEYBOARD MACRO

You could run this script in the same way as the Hello.vbs script was run, but it would be pointless. If you double clicked the Remove(n).vbs file then it would be the file highlighted and the effect of the script would be to rename the file to Remove.vbs.

We need to highlight a file of choice to be renamed and then execute the script. The way to do this is to assign a key combination to run the script. For example, if we set things up so that the key combination Ctrl-Alt-z ran the script then we could highlight the file whose name is to be changed and then press Ctrl-Alt-z. As the script will, after execution, highlight the next file in the Explorer window we could amend the names of a group of adjacent files simply by pressing Ctrl-Alt-z as many times as necessary. Even if the odd file in the window does not need its name amending we could press cursor down instead of Ctrl-Alt-z and then carry on.

Script Shortcut

Windows provides a means of assigning a key combination to run a file. You have to create a shortcut to the file ON THE DESKTOP. Creating a shortcut is not sufficient. It has to be on the desktop! Create a shortcut anywhere else and the key combination does not work. Whoever dreamt up this restriction of Windows functionality was obviously on the sauce on the day in question! Nevertheless, it does mean I have finally found a use for the desktop. I never start a program by clicking a desktop icon. I'm a clean desktop man and do not like it overrun with icons!

In the example we want to create a shortcut to C:\My Documents\WindowsScripts\Remove(n).vbs on the desktop. Do this as follows:

  • Right click the desktop and select New and Shortcut from the context menu.
  • Click the Browse button
  • Navigate to the C:\My Documents\WindowsScripts directory
  • Click the down arrow next to the 'Files of type' box and select All files
  • In the list of files displayed select Remove(n).vbs and click the Open button
  • Click the Next button
  • Give the shortcut a name, say Remove(n), and click the Finish button.
  • A shortcut with the name Remove(n) will appear on the desktop. Right click it and select Properties from the context menu.
  • Put the cursor in the Shortcut key box by clicking the box
  • Press Ctrl-Alt-z together
  • Click the OK button.

That is all there is to it. Any time you need the script to execute just press Ctrl-Alt-z.

CREATING OTHER KEYBOARD MACROS

Now that I have explained how to create this example keyboard macro you have the template to create others. You have two things to change in the script:

Replace the "Exploring" in the Wsh.AppActivate line with the start of the title of the windows in which the macro is to work.

Define the keys to send in the Wsh.SendKeys line.

Save the revised script as another file and create another shortcut on the desktop with a different key combination.

If you are only going to use the keyboard macros infrequently you may wish to create the desktop shortcut only at the time of use and always use the Ctrl-Alt-z combination for its Shortkey. It saves remembering lots of different combinations or choosing a combination which conflicts with a shortcut in the application being used.

CONCLUSION

I hope this discussion has opened your eyes as to the possibilities of Windows Scripting Host. I have already written my second script. I mentioned in the Blog at the beginning of the year a problem I was having at work, which I solved by an inelegant method of opening Explorer using Dynamic Data Exchange. It worked but, ever searching for the elegant method, I finally worked out a solution using a script, which did not use DDE at all. That script is now a fixture on my Office Shortcut Bar and my problem has gone away.

Dual Windows Explorer

I am thinking of returning to another problem that has been with me since the beginning of Windows 9x. How to open 2 instances of Windows Explorer and tile them horizontally over the full screen. In this way I can drag and drop copy like was done with the old File Manager. At present I create this interface manually, when I need it. How much easier it would be if I could write a script to do the creation for me.

Update
Here is the script for dual Explorer windows:

'A script to open Dual Windows Explorers on folders of the user's choice.
'
'The script should be called with TWO parameter which define the folders to open
'
Dim sa
Set sa = Wscript.CreateObject ("Shell.Application")
If WScript.Arguments.Count = 2 Then
sa.explore WScript.Arguments.Item(0)
sa.explore WScript.Arguments.Item(1)
Else
WScript.Echo "Please call this script with TWO argument to define the folders to open"
End If
Wscript.sleep(1)
sa.TileHorizontally()

Maybe you have some problems that can be solved with a script. Now that you know about WSH, take a look at it and see if you can solve those problems and discover the joy of being in control of Windows.

If you create some useful scripts please send them to me for upload. They can then be shared with the whole ICPUG community.

READER WRITES

Cesar writes to say:

I just read your web page where you describe the use Windows scripting. I’m having looking for several days this type of solution. I was wondering if you could give me a tip. I need to create a simple script that basically executes the {scroll} + {scroll} combination, as simple as that. Is this something I can do with Windows scripting. I appreciate your page, it is going to be very useful for certain issues I need to solve.

I see no problems with sending what Cesar wants. The Help file for Windows Scripting 5.6 says the keys are:

{SCROLLLOCK}{+}{SCROLLLOCK}

(Note: There are 3 'L's in SCROLLLOCK!)

UPDATE: 25 APRIL 2004

One of the keys that the SENDKEYS method of WSH will not emulate is the Windows key (beside the ALT keys on a Windows keyboard). Also, it is not possible to define the Windows key as the keyboard trigger for a desktop shortcut.

Mike Newman writes to tell me of a program, Winkey, that will allow you to write Windows-key keyboard shortcuts. It is a free download at:

http://download.com.com/3000-2344-913626.html?tag=lst-0-1

Another problem with WSH is that it cannot emulate the numeric keypad keys. This makes it impossible to create, for example, the character defined by pressing the ALT key in combination with the numeric keypad keys 0230. Microsoft Word has an alternative shortcut to this character, press CTRL-& followed by a, but this will not apply to all applications. Why would generation of this character be useful? Apparently, Esperanto writers use this and other symbols to write certain Esperanto characters that are not available in English. If anyone has a solution to this puzzle let me know.

Later articles in this series can be found here:
Esperanto and Plugging the Gaps in Windows Scripting Host
Esperanto and Other Characters - The Complete Solution


 

 

 

 


TOP