Guy's Scripting Ezine 120 - SendKeys
Whenever I review my previous Ezines it always surprises me which ezines are the most popular. The way I judge popularity is by the number of
page hits each ezine receives. Consistently, SendKeys featured in Ezine 26, wins the popularity stakes by a country mile. It is because of the level of interest that I am revisiting this topic, in
particular I want to be clear when to use SendKeys and when to seek alternative commands. This week I want to put VBScript's SendKeys method into perspective. As the name indicates, this method
literally sends keyboard keystrokes to the interface which is in focus when the script runs. I suggest that SendKeys has the following three scenarios when it will assist your scripts. 1) SendKeys is great if you just want to have a bit of fun;
it's ideal for practising your scripting
techniques in a harmless but enjoyable manner. For example, when you are learning how to open programs such as notepad, with a VBScript, you want some action, therefore you decide to send key strokes to
notepad programmatically. 2)
SendKeys is handy strategy when you are at an intermediate stage in your scripting project. You suspect that your script needs some smart scripting switches or program commands, but you just cannot find them. As a
stop-gap measure, until you can research something better, you fall back on SendKeys to issue instructions as though you were typing them at the keyboard. 3) SendKeys as a last resort. When all else
fails, hours of research fails to find that fancy switch, you turn to SendKeys in desperation. In these circumstances and for the short term, SendKeys will enable you to fulfil your objective, albeit with
risky commands.
Professional script writers don't trust SendKeys. The reason is because the results of sending keystrokes to applications are unpredictable and potentially catastrophic. Even if no users are involved, factors may change over time and
SendKeys instructions may be
delivering their keystrokes to entirely the wrong window. 99% of the time such an error will just result in a routine script failure, but there is a slim chance that the keystrokes could cripple the
server, or wipe a database. Professionals would not risk their reputation on SendKeys.
The only way to see what SendKeys has to offer is to experiment with an example or two. As a bonus we can use SendKeys as a vehicle to learn valuable techniques, which you can employ in other VBScripts,
for example the Set command and the Shell object. The methodology is to create our shell object then apply the sendkeys method followed by the keystrokes as a string. Note the placement of both the brackets and
of the speech marks. You could start with typing these commands into notepad and saving the resultant file with a .vbs extension. Once you have created Example 1, double click your file and observe
SendKeys in action.
set objShell = WScript.CreateObject("WScript.Shell")
Once you have created the shell object then you can send keystrokes to objShell. However, to be effective, we need our script to launch an application such as notepad or the cmd prompt.
set objShell = WScript.CreateObject("WScript.Shell") objShell.Run("cmd")
Now we are ready to start sending keys to the CMD prompt session. In this example we will merely execute a simple "dir" instruction, meaning list the directory contents.
set objShell = WScript.CreateObject("WScript.Shell") objShell.Run("cmd") objShell.SendKeys "dir"
Here is the full script with a few extras such as sleep delays, and a final command to exit the cmd prompt application and close the dos box.
' SendKeys.vbs Example Script ' VBScript to send keyboard strokes to command prompt ' Guy Thomas ' http://computerperformance.co.uk/ ' Version 2.1 - August 2006 '
--------------------------------------------------------' Option Explicit
Dim objShell, WshShell set objShell = CreateObject("WScript.Shell") objShell.Run("cmd") WScript.Sleep 500 objShell.SendKeys "dir" objShell.SendKeys "{Enter}"
WScript.Sleep 3500 objShell.SendKeys "Exit"
objShell.SendKeys "{Enter}"
WScript.Quit
' End of SendKeys Example Script
VBScript Learning PointsNote 1: My use of Sleep to pause the script is contentious. The reason that I employ this delay to help you trace and understand what is
happening. Professionals say, rightly, that in production scripts you should avoid Sleep commands and instead, let the program handle the timing with their own default routines. In a nutshell, there
is rarely any need for Sleep commands in production scripts. Note 2: The Script invokes CMD's own instruction to close, e.g. objShell
"Exit". Observe that the script still needs a carriage return sequence: objShell.SendKeys "{Enter}". See more special SendKeys instructions at the end of the ezine. Note 3: Furthermore, pay special attention to the curly brackets around "{Enter}" Variation ' set WshShell = WScript.CreateObject("WScript.Shell"). By analysing
this variation of Example 1, we gain what I call binocular vision. Question: is the tiny word 'set' important? The answer is yes 'set' is crucial and no, you must not change 'set' to any other verb.
WshShell or
objShell what is the difference. Nothing. Just a matter of personal choice, which name you use for your, observe how I declare employ Option Explicit to force me to declare all my variables.
In your scripts, will you use WScript.CreateObject or just plain CreateObject. I stick with CreateObject because it's shorter, clearer and it always works for me. Purists may argue that you
employ the longer WScript.CreateObject.
' SendKeysSub.vbs Example Script ' VBScript to send keyboard strokes to command prompt ' Guy Thomas ' http://computerperformance.co.uk/ ' Version 3.2 - August 2006 '
--------------------------------------------------------' Option Explicit
Dim objShell, WshShell, intSleep intSleep = 3500 ' set objShell = CreateObject("WScript.Shell") set
WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run("cmd") WScript.Sleep 500 WshShell.SendKeys "dir"
Call GuyClose WshShell.SendKeys "Exit"
Call GuyClose
sub GuyClose () WScript.Sleep intSleep WshShell.SendKeys "{Enter}" WScript.Sleep 200 End Sub WScript.Quit
' End of SendKeys Example Script
Note 1: I added the variable intSleep so that I can control the pauses between instructions from one place. Incidentally, a value of 1000 for intSleep means wait one
second. Note 2: Trace the sub-routine. Shamelessly, I rarely miss a chance to add a sub-routine to handle repetitive command sequences. Examine the brackets (), the End Sub, and
especially how I call the routine. Note 3: For this script I followed through and chose WshShell instead of objShell. As I mentioned earlier, you can choose what ever name you like for
the names of your variables.
If you are looking for handy network utilities, try some of the free downloads at
Tools4Ever
Guy's ChallengesChange the value .Sleep time. Try running other programs, for example .run("NotePad") Take a view on my sub-routine GuyClose(). My challenge is to rip it out or modify
it and thus learn a little about the value of sub-routines.
- 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}
SendKeys is a useful temporary measure for passing keystrokes to your program. By all means have some fun and learn this aspect of
VBScript. However, for production scripts always favour more reliable techniques.
Their topics and material are ideal for getting you started with VBScript. The
videos are easy to follow and you can control the pace. Try their free demo material and then see if you want to buy the full package.
See more about VB Script Training CD.
|