Specifically, you will learn how to • Create your own customized functions • Create reusable collections of statements using subroutines • Break down scripts into modules of code to make
Trang 1Set objNewShortcut = objWshShl.CreateShortcut(strAppDataPath + _
“\\GuessANumber.lnk”)
objNewShortcut.TargetPath = “C:\ GuessANumber.vbs”
objNewShortcut.Save
What makes working with the Quick Launch toolbar different than working with other Windows special folders is that you must specify the location of the Quick Launch toolbar within the special folder (AppData) that contains it
Figure 6.17 shows how the Quick Launch toolbar appears once the shortcut of your VBScript game has been added to it
A Complete Shortcut Script
Now let’s put together some of the shortcut examples you worked on previously to make a new script that creates shortcuts for GuessANumber.vbson the Windows desktop, Programs menu, and Quick Launch toolbar
‘*************************************************************************
‘Script Name: ShortcutMaker.vbs
‘Author: Jerry Ford
‘Created: 11/28/02
‘Description: This script creates shortcuts for the GuessANumber.vbs
‘VBScript ‘on the Windows desktop, Programs menu, & Quick Launch Toolbar.
‘*************************************************************************
‘Initialization Section
Option Explicit
Dim objWshShl, strTargetFolder, objDesktopShortcut, objProgramsShortcut
Dim strAppDataPath, objQuickLaunchShortcut
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 6.17
Examining the
Windows Quick
Launch toolbar
after adding a
shortcut to
the GuessA
Number.vbs
game.
Guess a Number
Trang 2‘Establish an instance of the WshShell object
Set objWshShl = WScript.CreateObject(“WScript.Shell”)
‘Create the Desktop shortcut
strTargetFolder = objWshShl.SpecialFolders(“Desktop”)
Set objDesktopShortcut = objWshShl.CreateShortcut(strTargetFolder +
“\\GuessANumber.lnk”)
objDesktopShortcut.TargetPath = “C:\ GuessANumber.vbs”
objDesktopShortcut.Description = “Guess a Number Game”
objDesktopShortcut.Hotkey = “CTRL+Alt+G”
objDesktopShortcut.Save
‘Create the Programs menu shortcut
strTargetFolder = objWshShl.SpecialFolders(“Programs”)
Set objProgramsShortcut = objWshShl.CreateShortcut(strTargetFolder &
“\\GuessANumber.lnk”)
objProgramsShortcut.TargetPath = “c:\ GuessANumber.vbs”
objProgramsShortcut.Save
‘Create the Quick Launch Toolbar shortcut
strTargetFolder = objWshShl.SpecialFolders(“AppData”)
strAppDataPath = strTargetFolder + “\Microsoft\Internet Explorer\Quick Launch”
Set objQuickLaunchShortcut = objWshShl.CreateShortcut(strAppDataPath +
“\\GuessANumber.lnk”)
objQuickLaunchShortcut.TargetPath = “C:\ GuessANumber.vbs”
objQuickLaunchShortcut.Save
I achieved a few economies of scale here First of all, I only had to instantiate the WshShell object once I also reused the strTargetFolder variable over and over again However, I thought that it made the script more readable to assign a different variable to each special folder reference Run this script and you should see shortcuts for GuessANumber.vbsadded to the Windows desktop, Programs Menu, and Quick Launch toolbar
Summary
In this chapter you learned about loops and how to apply them to your VBScripts You demonstrated your understanding of this fundamental programming concept through the development of the Guess a Number game You also leaned how to programmatically work with Windows shortcuts, and how to use them to create shortcuts for your scripts, as well
as how to configure a number of Windows features, including the Windows desktop, Start Menu, and Quick Launch toolbar
Trang 3202 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
CH A L L E N G E S
1 Modify the Guess a Number Game by providing the players with better hints For example, if a user’s guess is within 20 numbers of the answer, tell the player that
he is getting warm As the player gets even closer to the correct guess, tell him that he is getting very hot.
2 Change the Guess a Number game to increase the range of numbers from 1 to
100 to 1 to 1000.
3 Rewrite the Pick a Number Game so it uses a Do While statement in place of a
Do Until statement.
4 Use ShortcutMaker.vbs as a starting point, and write a new script that creates one
or more shortcuts for your favorite VBScript game Alternatively, if you keep all your VBScripts in one location, create a shortcut to that folder.
Trang 4Using Procedures
to Organize
Scripts
7
By now you’ve seen and worked on a number of VBScript projects in this
book, and all of these scripts have been organized the same way First, you’ve set up script initialization processes (defining variables, constants, objects, and so on), and then you sequentially wrote the rest of the script as one big collection of statements You’ve then used the Ifand Select Casestatements
to organize your scripts Finally, by embedding statements within one another you have further refined your scripts’ organization In this chapter, you will learn how to further improve the organization of your VBScripts, using procedures Specifically, you will learn how to
• Create your own customized functions
• Create reusable collections of statements using subroutines
• Break down scripts into modules of code to make them easier to manage
• Control variable scope within your scripts using procedures
Project Preview: The BlackJack Lite Game
In this chapter, you create a game called BlackJack Lite This game is based on the classic blackjack game played in casinos around the world In this game, both the player and the computer are dealt a single card, face up The object of the game
is to try to get as close as possible to a value of 21 without going over The player can ask for as many extra cards (hits) as desired and can stop (stick) at any time
Trang 5If the player goes over 21, he or she busts Otherwise the computer plays its hand, stopping only after either reaching a total of 17 or more or busting Figures 7.1 through 7.5 demon-strate the game in action
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 7.1
The game’s splash
screen invites
the user to play
a game of
BlackJack Lite.
Figure 7.2
If the user
declines, the
game displays
information about
itself and its
author and invites
the user to play
later.
Figure 7.3
If the user
accepts the offer
to play, the initial
hands are dealt.
Trang 6By the time you’ve worked your way through this chapter and completed the BlackJack Lite game, you will have gained a solid understanding of how to use procedures You will be able
to improve the overall organization and functionality of your VBScripts and tackle even more challenging projects
Improving Script Design with Procedures
VBScript procedures improve the overall organization
and readability of scripts giving you a way to group
related statements and execute them as a unit Once
written, a VBScript procedure can be called on from
any location in your script and can be executed over
and over again as needed This enables you to create
scripts that are smaller and easier to maintain
VBScript provides support for two different types of procedures
• Sub A VBScript procedure that executes a set of statements without returning a result
• Function A VBScript procedure that executes a set of statements and, optionally, returns a result to the statement that called it
Figure 7.4
The user plays
until either
busting or
holding.
Figure 7.5
The computer
then plays and
the results of the
game are shown.
Definition
A procedure is simply a collection
of VBScript statements that, when called, are executed as a unit.
Trang 7I recommend using procedures as the primary organization tool for all VBScripts
By organizing a script into procedures, you break it down into a collection of units This allows you to separate processes from one another, making it easier to develop scripts in a modular fashion, one component at a time
Introducing Subroutines
The VBScript Subprocedure is used to create subroutines Subroutines are great for group-ing together statements that perform a common task from which a result is not required When called, subroutines execute their statements and then return processing control back
to the calling statement
The syntax for this type of procedure is as follows:
[Public | Private] Sub name [(arglist)]
statements
End Sub
Privateis an optional keyword that specifies the subroutine cannot be called by other pro-cedures within the script, thus limiting the ability to reference it Publicis an optional key-word that specifies the subroutine can be called by other procedures within the script name
is the name assigned to the subroutine Like variables, a subroutine’s name must be unique within the script that defines it arglistrepresents a list of one or more comma-separated arguments that can be passed to the subroutine for processing, and statementsrepresents the statements that make up the subroutine
For example, the next subroutine is called DisplaySplashScreen() It does not accept any arguments and it does not return anything back to the VBScript statement that calls it What it does is display a script’s splash screen any time it is called
Sub DisplaySplashScreen()
MsgBox “Thank you for playing the game © Jerry Ford 2002.” & _
vbCrLf & vbCrLf & “Please play again soon!”, 4144, “Test Game”
End Sub
You can execute this subroutine by calling it from anywhere within your script using the fol-lowing statement:
DisplaySplashScreen()
The following example is a rewrite of the previous subroutine; only this time the subroutine has been rewritten to accept an argument The argument passed to the subroutine will be a
T R I C K
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Trang 8message Using a subroutine in this manner, you can develop scripts that display all their pop-up dialogs using one subroutine
Sub DisplaySplashScreen(strMessage)
MsgBox strMessage, 4144, “Test Game”
End Sub
You can call this subroutine from anywhere within your script like this:
DisplaySplashScreen(“Thank you for playing the game © Jerry Ford “ &_
“2002.” & vbCrLf & vbCrLf & “Please play again soon!”)
Creating Custom Functions
Functions are almost exactly like subroutines Functions can do anything that a subroutine can do In addition, a function can return a result back to the statement that called it As a result (to keep things simple), I usually use functions only within my VBScripts
The syntax for a function is as follows:
[Public | Private] Function name [(arglist)]
statements
End Function
Private is an optional keyword that specifies that the function cannot be called by other procedures within the script, thus limiting the ability to reference it Publicis an optional keyword that specifies that the function can be called by other procedures within the script nameis the name assigned to the function Like variables, a function’s name must be unique within the script that defines it arglistrepresents a list of one or more comma-separated arguments that can be passed to the function for processing, and statementsrepresents the statements that make up the function
Let’s look at an example of a function that does not return a result to its calling statement Function DisplaySplashScreen()
MsgBox “Thank you for playing the game © Jerry Ford 2002.” & _
vbCrLf & vbCrLf & “Please play again soon!”, 4144, “Test Game”
End Function
As written, this function performs the exact same operation as the subroutine you saw previ-ously This function can be called from anywhere in your script using the following statement: DisplaySplashScreen()
Trang 9As with subroutines, you may pass any number of arguments to your functions, as long as commas separate the arguments, like this:
Function DisplaySplashScreen(strMessage)
MsgBox strMessage, 4144, “Test Game”
End Function
Once again, this function is no different from the corresponding subroutine example you just saw, and can be called as follows:
DisplaySplashScreen(“Thank you for playing the game © Jerry Ford “ &_
“2002.” & vbCrLf & vbCrLf & “Please play again soon
Functions also can be set up to return a result to their calling statement This is achieved by creating a variable within the function that has the same name as the function, and by set-ting the variable equal to the result that you want the function to return
Again, this technique can best be demonstrated with an example
strPlayersName = GetPlayersName()
MsgBox “Greetings “ & strPlayersName
Function GetPlayersName()
GetPlayersName = InputBox(“What is your first name?”)
End Function
The first statement calls a function name GetPlayersName() The second statement displays the results returned by the function and stored in the variable called PlayersName The next three lines are the actual function, which consists of a single statement that collects the player’s name and assigns it to a variable named GetPlayersNameso that it can be passed back
to the calling statement
Another way to call a function is to reference it as part of another VBScript statement, like this:
MsgBox “Greeting “ & GetPlayersName()
Improving Script Manageability
As I said before, by organizing your VBScripts into procedures, you make them more man-ageable, allowing you to create larger and more complex scripts without adding mounds of complexity As an example, let’s say that you’re developing a game that performs the five major activities that follow:
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Trang 10• Initializes variables, constants, and objects used by the script
• Asks the player whether he or she wants to play the game
• Collects the player’s name
• Displays a story, substituting the player’s name at predetermined locations within the story
• Displays a closing dialog inviting the player to play again on another day
One way to design your script would be to first define the variables, constants, and object references, and then create a series of functions and subroutine calls from the script’s main processing section The rest of the script would then consist of individual functions and sub-routines, each of which would be designed to perform one of the activities outlined in the previous list
Writing Reusable Code
One of the biggest advantages provided by functions and subroutines is the capability to create reusable code within your VBScripts Any time you find yourself needing to perform the same task over and over in a script—such as displaying messages in popup dialogs or retrieving random numbers—consider creating a function or subroutine Then, by using a single statement to call the appropriate procedure, you can reuse the statements located within the procedure over and over again
Functions and subroutines help make for smaller scripts They also make script mainte-nance and enhancement much easier and quicker For example, it’s a lot easier to change one line of code located in a procedure than it is to make that same change in numerous places throughout a script
In the Real World
One sign of a world-class programmer is the path that he or she leaves behind—in other words, the professional way in which the programmer organizes and documents his or her scripts One organizational technique used by experienced programmers is to group all functions and subroutines together in one place, apart from the initialization and main processing sections
of the script This makes them easy to locate and maintain Usually, you’ll find a script’s func-tions and subroutines located at the bottom of the script I suggest that you modify your script template to include a Procedure section for this purpose.