[Previous] [Table of Contents] [Next]

Using Internet Explorer and WSH to Create a Form

Now let's apply the techniques we just discussed to create a form for user input. Again, we'll use Internet Explorer and an HTML page. An HTML form can contain text boxes, option buttons, check boxes, and numerous other features. (Figure 9-2 shows a simple form with two text boxes.) The only difficult part is accessing the form in the browser window from your WSH script.

Figure 9-2 An input form

HTML Code for the Form

An HTML form is an HTML document with a few special HTML tags. You can use Microsoft FrontPage Express or any other HTML editor to insert the items for the form into the document.

The HTML code in Listing 9-5 creates the form shown in Figure 9-2.

Listing 9-5 HTML code for creating a form

<html>
    <head>
        <title>Form input - by G. Born</title>
    </head>
    <body bgcolor="silver" scroll="no">
        <form name="ValidForm">
            Name:  
            <input name="fName" type="TEXT" size="5">&nbsp;
            Age:
            <input name="fAge" type="TEXT" size="3">
        </form>
    </body>
</html>

The title of the form's window is defined in the <head> block using the <title> tag. The background color of the form is specified in the <body> tag using the bgcolor attribute, which is set to "silver". This sets a gray background for the form. The attribute scroll="no" causes Internet Explorer to hide the vertical scroll bar. The commands for creating the form are embedded in the <form> …</form> tags. The name attribute of the starting tag gives the form a unique name. We'll need this name later.

The two controls in the form are created using <input> tags. The <input> tag has the following syntax:

<input name="fName" type="TEXT" size="5">

The name attribute defines the name of the control. The type attribute defines the type of control (text box, button, and so forth). The size attribute defines the size (character length) of a control. If you store these HTML tags in an HTML file and load this file in Internet Explorer, a form is displayed.

NOTE
I omitted a Close button (as shown in the About dialog box sample) because if an onclick event on a Close button calls the window.close method, a browser dialog box appears asking the user whether to close the window. Converting the .htm file to .hta doesn't change this behavior because Windows won't load an HTA application in the requested order. I decided to just let the user close the form using the default Close button in the upper right corner of the browser window. Later I'll show a different solution that includes a Close button in the form.

Displaying the Form

Now let's write a WSH script, implemented in VBScript, to use the form. The script launches Internet Explorer, loads the HTML file containing the form, and reads the user input from the form.

The following code sequence loads Internet Explorer and displays the form:

Set oIE = CreateObject("InternetExplorer.Application", "IE_")

oIE.Left = 50           ' Window position and other properties
oIE.Top = 100 
oIE.Height = 100
oIE.Width = 280
oIE.MenuBar = 0         ' Disable some bars.
oIE.ToolBar = 0
oIE.StatusBar = 0
' oIE.Resizable = 0      ' Disable resizing.

oIE.navigate path & "Form1.htm"  ' Form

oIE.Visible = 1         ' Show document window.

The Set keyword in the first line assigns a reference to Internet Explorer's Application object. This object variable allows you to access the Internet Explorer object model with all its properties. The second parameter submitted to the CreateObject method defines the prefix used in event handling procedures. It enables WSH to connect events raised from the object to the event handlers in the script. (See also the Chapter 7 sections dealing with CreateObject and DisconnectObject.) I'll use this technique here to detect when the user has closed the form.

You can set the window position and size in the WSH script using the Left, Top, Height, and Width properties. To disable the menu bar, the status bar, and so on, you set the associated Internet Explorer properties (MenuBar, ToolBar, and StatusBar) to 0.

NOTE
The statement oIE.Resizable = 0 disables document window resizing. I commented out this statement because Internet Explorer versions 4 and 5 render the form's border incorrectly on my system if the property is set.

You load the HTML file using the following statement:

oIE.navigate GetPath() & "Form1.htm"

I moved the statements (used in the previous sample) that extract the current folder into a procedure named GetPath. I mentioned earlier that the Script object isn't accessible until Internet Explorer loads a document. Therefore, you must use the following code to test Internet Explorer's Busy property. The following loop is processed in the WSH script until Internet Explorer reports that the form has been loaded:

Do While (oIE.Busy)
    WScript.Sleep 200
Loop

Internet Explorer sets this property to True when it loads a document and resets it to False when the document finishes loading. The WScript.Sleep call suspends the script during each pass (which lowers the CPU load).

After loading the form, we have a slight problem: the WSH script and the browser window displaying the form are two independent processes, so the WSH script must wait until the user closes the form. I decided to use the following strategy:

You can then query the form's state by using the following code:

Do While (Not ready)
    WScript.Sleep 500   ' Suspend for 0.5 second.
Loop

Closing the browser window raises the onclose event. The script's event handling procedure reads the user input and sets the variable ready to True. After exiting the loop, the script uses a simple MsgBox call to display the user input. (See Figure 9-3.)

Figure 9-3 The results shown in a WSH script dialog box

Now let's take a closer look at the event handling procedure. It contains the following script code:

Sub IE_OnQuit()
    ' Event handler is called if IE terminates.
    ' This happens if the user clicks the OK button.
    ' Retrieve the values.
    name = "Name: " & oIE.Document.ValidForm.fName.Value
    age = "Age: " & oIE.Document.ValidForm.fAge.Value
    ready = True        ' Indicate form is closed.
End Sub

The first statement retrieves the user input in the Name text box and stores it in the global variable name. You can use this global variable in the script's main routine.

I'd like to say a word about how to obtain the user input from the text box. The statement uses the following object hierarchy:

oIE.Document.ValidForm.fName.Value

oIE is the object variable pointing to Internet Explorer's application object, and the form is loaded in its subobject Document. I assigned the object name ValidForm to the form using the name attribute in the HTML code. I did the same with the name attribute of each control element. ValidForm.fName identifies the first text box in the form, and the Value attribute of this object contains the user input as a text string. After reading both values and saving them in global variables, the event handler sets the ready state to True. Then it terminates and allows Internet Explorer to close the browser window.

The entire WSH script source code is shown in Listing 9-6.

Listing 9-6 Form1.vbs

'************************************************
' File:    Form1.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born
'
' Using Internet Explorer 4 or 5 to retrieve
' form input
'************************************************
Option Explicit

Const Title = "WSH sample form input - by G. Born"
Dim oIE      ' Internet Explorer object
Dim path     ' Path to script file
Dim ready    ' State of the form (True = form closed)

Dim Text2
Dim name, age ' Values obtained from form

Text2 = "You entered:" & vbCrLf

' Launch Internet Explorer, and connect event handler.
Set oIE = WScript.CreateObject("InternetExplorer.Application", "IE_")


oIE.Left = 50           ' Window position and other properties
oIE.Top = 100 
oIE.Height = 100
oIE.Width = 280
oIE.MenuBar = 0         ' No menu
oIE.ToolBar = 0
oIE.StatusBar = 0
' Commented out because it causes a corrupted window border. 
' oIE.Resizable = 0     ' Disable resizing.
oIE.navigate GetPath() & "Form1.htm"  ' Load form.
oIE.Visible = 1         ' Keep visible.

' Important: wait until Internet Explorer is ready.
Do While (oIE.Busy)    
    WScript.Sleep 200   ' Suspend for 200 milliseconds.  
Loop

ready = False           ' Form is still open.
   
' Wait until the user closes the form using
' the Close button in the upper right corner of the window.
' This sets ready to True in the onclose event.

Do While (Not ready)    ' Wait until form is closed.
    WScript.Sleep 500   ' Suspend for 500 milliseconds.
Loop

' Display the data obtained in the event handling procedure.
MsgBox Text2 & vbCrLf & name & vbCrLf & age, _
             vbOKOnly + vbInformation + vbSystemModal, Title

' We're ready now. The sample script terminates.
' Here you can add script-specific code.

' Event handler and helper

Sub IE_OnQuit()
    ' Event handler is called if IE terminates.
    ' This happens if the user clicks the Close button.
    ' Retrieve the values.
    name = "Name: " & oIE.Document.ValidForm.fName.Value
    age = "Age: " & oIE.Document.ValidForm.fAge.Value
    ready = True        ' Indicate form is closed.
End Sub

Function GetPath()
    ' Get script path because the form (HTML file)
    ' must be in the same folder.
    Dim path
    path = WScript.ScriptFullName
    GetPath = Left(path, InStrRev(path, "\"))
End Function

'*** End

A JScript WSH Script for Displaying the Form

If you prefer to use JScript for WSH scripts, you can port the VBScript program to JScript. You simply have to consider the different syntax. The only changes you have to make are to the WSH script because the script in the HTML document is independent. You must also pay attention to case sensitivity in method and object names.

By the way, JScript doesn't support some VBScript functions, such as Left for extracting the path. You must use the substr method of the String object instead. The position of the last \ character is returned from the lastIndexOf method of the String object. Listing 9-7 shows the JScript equivalent of Form1.vbs.

Listing 9-7 Form1.js

//************************************************
// File:    Form1.js (WSH sample in JScript) 
// Author:  (c) G. Born
//
// Using Internet Explorer 4 or 5 to retrieve
// form input
//************************************************
var Text2 = "You entered:\n";

// Launch Internet Explorer, and connect event handler.
var oIE = WScript.CreateObject("InternetExplorer.Application", "IE_");

oIE.Left = 50;           // Window position and other properties
oIE.Top = 100; 
oIE.Height = 100;
oIE.Width = 280;
oIE.MenuBar = 0;         // No menu
oIE.ToolBar = 0;
oIE.StatusBar = 0;
// Commented out because it causes a corrupted window border. 
// oIE.Resizable = 0     // Disable resizing.
oIE.navigate(GetPath() + "Form1.htm");  // Load form.
oIE.Visible = 1;         // Keep visible.

// Important: Wait until IE is ready.
while (oIE.Busy) {WScript.Sleep(200)}  // Suspend 

var ready = false;      // Form is still open.
   
// Wait until the user closes the form using
// the Close button in the upper right corner of the window.
// This sets ready to true in the onclose event.
while (!ready) {WScript.Sleep(500)}  // Suspend 

// Display the data obtained in the event handling procedure.
WScript.Echo(Text2 + "\n" + name + "\n" + age);

// We're ready now. The sample script terminates.
// Here you can add script-specific code.

// Event handler and helper

function IE_OnQuit()
{
    // Event handler is called if IE terminates.
    // This happens if the user clicks the Close button.
    // Retrieve the values.
    name = "Name: " + oIE.Document.ValidForm.fName.value;
    age = "Age: " + oIE.Document.ValidForm.fAge.value;
    ready = true;        // Indicate form is closed.
}

function GetPath()
{
    // Get script path because form (HTML file)
    // must be in the same folder.
    var path = WScript.ScriptFullName;
    path = path.substr(0, path.lastIndexOf("\\") + 1);
    return path;
}

//*** End

Displaying a File Selection Dialog Box

Sometimes a script needs a way to let the user select a file for further processing. WSH doesn't offer a method that displays a file selection dialog box. In Chapter 12, I'll discuss how to use the Browse For Folder dialog box to select drives, files, or folders, but this isn't the best solution. Now that you know how to use Internet Explorer as a front end, you can use a neat trick: you can use a form with a Browse button that allows the user to select a file using the default Windows dialog box. (See Figure 9-4.) You can write the HTML tag to display the text box and the Browse button as follows:

<input type="file" size="75" name="fFile">

The <input> tag is the same one we used in the previous sample to create a text box. If the type attribute is set to "file", a text box and a Browse button are shown in the form. The size attribute defines the length of the text box, and the name attribute defines an object name for this control. The caption Browse is already rendered by the browser. (The caption depends on the localized browser version.)

Click to view at full size.

Figure 9-4 Displaying a Choose File dialog box from a WSH script

The form includes a text box and a Browse button. (See Figure 9-4, left.) If the user clicks the Browse button, the browser opens the Choose File dialog box (Figure 9-4, right) and allows the user to select a file. After the user closes the dialog box, the selected file, including its path, is shown in the text box.

The code for handling the Choose File dialog box is based on the previous sample. I changed only a few messages and the name of the text box control. Listing 9-8 shows the implementation in JScript.

Listing 9-8 Form2.js

//************************************************
// File:    Form2.js (WSH sample in JScript) 
// Author:  (c) G. Born
//
// Using Internet Explorer 4 or 5 to display
// a file selection dialog
//************************************************
var Text2 = "File selected:\n";

// Launch Internet Explorer, and connect event handlers.
var oIE = WScript.CreateObject("InternetExplorer.Application", "IE_");
var file = "";           // Initialize file name.

oIE.Left = 50;           // Window position and other properties
oIE.Top = 100; 
oIE.Height = 200;
oIE.Width = 580;
oIE.MenuBar = 0;         // No menu
oIE.ToolBar = 0;
oIE.StatusBar = 0;
// Commented out because it causes a corrupted window border. 
// oIE.Resizable = 0     // Disable resizing.
oIE.navigate(GetPath() + "Form2.htm");  // Load form.
oIE.Visible = 1;         // Keep visible.

// Important: Wait till IE is ready
while (oIE.Busy) {WScript.Sleep(200)}  // Suspend 

var ready = false;      // Form still open
   
// Wait until the user closes the form using
// the Close button in the upper right window corner.
// This sets ready to true in the onclose event.
while (!ready) {WScript.Sleep(500)}  // Suspend 

// Display the file name obtained in the event handling procedure.
WScript.Echo(Text2 + "\n" + file);

// We are ready now; the sample script terminates here.
// Here you can add script-specific code.

// Event handler and helper

function IE_OnQuit()
{
    // Event handler called when IE terminates.
    // This is the case if the user clicked the Close button.
    // Retrieve the values.
    file = oIE.Document.ValidForm.fFile.value;
    ready = true;        // Indicate form is closed
}

function GetPath()
{
    // Get script path because form (HTML file)
    // must be in the same folder.
    var path = WScript.ScriptFullName;
    path = path.substr(0, path.lastIndexOf("\\") + 1);
    return path;
}

//*** End

Improving the Form

The problem with the preceding samples is that they don't include an OK button that allows the user to confirm the input. An improved solution should follow these guidelines:

Using this approach, the HTML document contains only a small script, which provides the rudimentary functions for retrieving the form's state. You access the form's values directly from the WSH script (as shown previously).

Creating the HTML form

The first step in implementing a user input form is to create an HTML document that provides the necessary form elements. The simplest method is to use an HTML editor such as Microsoft FrontPage or FrontPage Express to create an HTML document containing the form. After you design the form, you must alter the HTML source code and add a few scripts. Figure 9-5 shows an extended HTML form and a WSH dialog box with the user input retrieved from that form.

Click to view at full size.

Figure 9-5 An extended form and the results in a WSH script dialog box

Here are the HTML tags for creating the form:

<form name="ValidForm">
    <p>
        Name: &nbsp;
        <input type="text" size="5" name="fName"> &nbsp;
        Age: &nbsp;
        <input type="text" size="3" name="fAge">
        <br>

        Password: &nbsp; 
        <input type="password" size="12" maxlength="8" name="fPassw">
        &nbsp; &nbsp; 
        <input type="button" name="Button1" value="OK">
        <br>

        <input type="checkbox" name="fPrinter" value="1" checked>
        Printer &nbsp;
        <input type="checkbox" name="fScreen" value="2">
        Screen
        <br>

        Remarks:
        <br> 

        <textarea cols="40" rows="5" name="fRemark">
        </textarea>
    </p>
</form>

The form is embedded in the <form> … </form> tags. The name attribute of the <form> tag specifies the object name (which you'll need later to access the form items in your scripts). Each form element is given a unique name in its own HTML tag.

You insert a text box using this code:

<input type="text" size="5" name="fName">

The type attribute specifies the form element's type. You can set the size attribute to restrict the size of the text box. The name attribute is required for each tag because it allows you to identify the item later in the scripts.

A text area input field requires the <textarea> …</textarea> tags. The <textarea> tag is ideal for collecting large amounts of text data. By combining <input> and <textarea> tags, you should be able to create any desired form.

After building your form, you need a few helper functions in the HTML document. You can initialize the form items when the document is loaded by using this procedure:

Sub Window_OnLoad()
    ' Here we can initialize the form (optional).
    Set TheForm = Document.ValidForm  ' Retrieve object.
    TheForm.fName.Value = ""   ' Initialize fName control value.
    ready = 0 ' User input not ready.
End Sub

The Window_OnLoad event procedure is invoked when the HTML document is loaded. The procedure shown above uses the (optional) statement to retrieve the form's object reference and assign it to the object variable TheForm. You can use this (optional) code to set the content of the first text box (with the name fName) to an empty string:

TheForm.fName.Value = ""      ' Initialize fName control value.

If necessary, you can add statements to initialize the other form items. (This example doesn't need them.)

The last statement is required:

ready = 0 ' User input not ready.

The browser containing the form runs as an asynchronous process, so you need some mechanism to coordinate the browser and the VBScript/JScript program. This sample uses the variable ready as a flag to indicate whether the user clicked the form's OK button. When the form is loaded, ready is set to 0 (which means that the form is still in input mode).

The user can fill in the fields in the form and click the OK button to release the form and return control to the script. I mentioned that the HTML document browser process runs independently of the WSH script process. To force Internet Explorer to close the browser window (after first displaying a warning dialog box and asking the user for confirmation), you can add the following to the <input> tag of the OK button:

onclick = "window.close()"

As mentioned earlier, I wasn't successful in using an HTA form from a script to avoid this behavior, so I decided to take a different approach: having the onclick event be handled within the HTML script in the document itself. As a result, the WSH script must close the form.

The next HTML sample uses a simple trick to tell the WSH script that the user has clicked the OK button. The OnClick event procedure of the Button1 object is called when the user clicks the OK button, and the ready value is set to 1.

Sub Button1_OnClick
    ' If the user clicks OK, we must signal the polling 
    ' WSH script by setting the ready flag.
    ready = 1 ' User input is ready.
End Sub

To have the WSH script check the internal state of the ready value, you can implement another small function, CheckVal:

Public Function CheckVal()
    ' This function is called from the host to check whether
    ' the user clicked the OK button.
    CheckVal = ready
End Function

CheckVal returns the ready value. If this value is set to 1, the WSH script knows that the OK button was clicked.

The entire HTML source code is shown in Listing 9-9.

Listing 9-9 Form3.htm

<html>
    <head>
        <meta http-equiv="Content-Type"
              content="text/html; charset=iso-8859-1">
        <meta name="GENERATOR" 
              content="Microsoft FrontPage Express 2.0">
        <title>
            Form input - by G. Born
        </title>
    </head>

    <body bgcolor="#C0C0C0" scroll="no">
        <script language="VBScript"> 
        <!--
            Dim ready 
            Public TheForm 

            Sub Button1_OnClick
                ' If the user clicks OK, we must signal the polling 
                ' WSH script by setting the ready flag.
                ready = 1 ' User input is ready.
            End Sub

            Sub Window_OnLoad()
                ' Here we can initialize the form.
                Set TheForm = Document.ValidForm
                TheForm.fName.Value = "" 
                ready = 0 ' User input not ready.
            End Sub

            Public Function CheckVal()
                ' This function is called from the host to check
                ' whether the user clicked the OK button.
                CheckVal = ready
            End function

        '-->
        </script>

        <h3>
            Form
        </h3>

        <hr>
            <form name="ValidForm">
                <p>
                    Name: &nbsp;
                    <input type="text" size="5" name="fName"> &nbsp;
                    Age: &nbsp;
                    <input type="text" size="3" name="fAge">
                    <br>

                    Password: &nbsp; 
                    <input type="password" size="12" maxlength="8" 
                           name="fPassw">
                    &nbsp; &nbsp; 
                    <input type="button" name="Button1" value="OK">
                    <br>

                    <input type="checkbox" name="fPrinter" value="1" 
                           checked>
                    Printer &nbsp;
                    <input type="checkbox" name="fScreen" value="2">
                    Screen
                    <br>

                    Remarks:
                    <br> 

                    <textarea cols="40" rows="5" name="fRemark">
                    </textarea>
                </p>
            </form>
        </hr>
    </body>
</html>

TIP
After you've created the form, you can store it as a template (because it already contains the necessary script code). To create a new form, load the script in a tool such as Microsoft FrontPage and alter or add the necessary controls to the form. After storing the result in a new HTML file, all you need to do is customize the WSH script to handle the controls of this form. But the HTML script code remains unaltered.

Displaying the HTML form

Now that you have an HTML document containing a form and a few script functions, you need a WSH script to invoke the form and retrieve the user input. The script must launch an instance of Internet Explorer, load the HTML document into the browser, and scan the ready state of the HTML document. You've already seen the basic techniques in earlier samples.

The user can fill in all the form's text boxes and click the OK button to close the form. At this point, you need a trick for the WSH script to recognize that the user has clicked the OK button. Earlier I introduced the CheckVal function, which returns the ready value to the caller. The following code sequence in the WSH script loops until the ready value is set to 1, which indicates that the user has clicked OK.

' Wait until the user clicks the OK button.
' Use the CheckVal function.
Do ' Wait for results.
Loop While (oIE.Document.Script.CheckVal() = 0)

The oIE object variable points to the Application object of the Internet Explorer process, which is the parent object of the Document.Script objects.

After the loop exits, all the user input is accessible. You'll recall from previous samples how to access the form's input value. To access the first text box, fName, you can use the following statement:

oIE.Document.ValidForm.fName.value

The value property contains the value the user entered into the text box fName. (Note that the names are case-sensitive if you use JScript to access the form's data.) This value is always provided as a string. Using similar code, you can access any form item from your WSH script. If you need to check user input, you can evaluate the values. If a value is unacceptable, you can display a message box to that effect.

By the way, you can also use this technique to write data to the form's control elements. You can do this to initialize the text box values from the script.

After you retrieve all values from the form, you can close the form by using this command:

oIE.Quit

This command executes the Quit method provided by the object referenced in the oIE object variable, causing Internet Explorer to close the HTML document and terminate the application. The values obtained from the form are displayed using a MsgBox call. By the way, the constant vbSystemModal used within the MsgBox call forces Windows to always display the dialog box in the foreground. Listing 9-10 is the entire VBScript program.

Listing 9-10 Form3.vbs

'************************************************
' File:    Form3.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born
'
' Using Internet Explorer 4 or 5 to retrieve
' form input
'************************************************
Option Explicit

Const Title = "WSH sample form input - by G. Born"

Dim oIE      ' Internet Explorer object

' Global variables for form values
Dim name, age, password, printer, screen, remark
Dim Text2

Text2 = "You entered:" & vbCrLf

' *** Launch Internet Explorer. ***
Set oIE = WScript.CreateObject("InternetExplorer.Application")

oIE.Left = 50           ' Window position and other properties
oIE.Top = 100 
oIE.Height = 380
oIE.Width = 450
oIE.MenuBar = 0         ' No menu
oIE.ToolBar = 0
oIE.StatusBar = 0
' Commented out because it causes a corrupted window.  
' oIE.Resizable = 0      ' Disable resizing.
oIE.navigate GetPath() & "Form3.htm"  ' Form
oIE.Visible = 1         ' Keep visible.

' Important: wait until Internet Explorer is ready.
Do While (oIE.Busy)      
    WScript.Sleep 200    ' Suspend for 0.2 second.
Loop

' Try to initialize the text box value from the script.
oIE.Document.ValidForm.fRemark.Value = "No remarks"

' Wait until the user clicks the OK button.
' Use the CheckVal function.
On Error Resume Next   ' Handle case in which IE is closed.
Do                     ' Wait until the OK button is clicked.
    WScript.Sleep 200  ' Suspend for 0.2 second.
Loop While (oIE.Document.Script.CheckVal() = 0)

' If an error occurs because the form is closed, quit the
' script.
If Err <> 0 Then
    WScript.Echo "Sorry, a run-time error occurred while checking" & _
                 " the OK button " & vbCrLf & _
                 "Error: " & Err.Number & " " & _
                 "I guess the form was closed; no input values..."
    WScript.Quit        ' End script.
End If

On Error GoTo 0    ' Switch off error handling. 

' User clicked the OK button; retrieve the values.
name = "Name: " & oIE.Document.ValidForm.fName.Value
age = "Age: " & oIE.Document.ValidForm.fAge.Value
password = "Password: " & oIE.Document.ValidForm.fPassw.Value
printer = "Printer: " & oIE.Document.ValidForm.fPrinter.Value _
          & " Status: " & oIE.Document.ValidForm.fPrinter.Checked
screen = "Screen: " & oIE.Document.ValidForm.fScreen.Value _
         & " Status: " & oIE.Document.ValidForm.fScreen.Checked
remark = "Remarks: " & oIE.Document.ValidForm.fRemark.Value
MsgBox Text2 & vbCrLf & name & vbCrLf & _
       age & vbCrLf & password & vbCrLf & _
       printer & vbCrLf & screen & vbCrLf & _
       remark, vbOKOnly + vbInformation + vbSystemModal, Title

oIE.Quit             ' Close Internet Explorer.
Set oIE = Nothing    ' Reset object variable.

' We're ready.

Function GetPath()
' Get script path because the form (HTML file)
' must be in the same folder.
    Dim path
    path = WScript.ScriptFullName
    GetPath = Left(path, InStrRev(path, "\"))
End Function

'*** End

The JScript implementation

The JScript implementation (Listing 9-11) uses a similar approach. Note the case sensitivity of variable names.

Listing 9-11 Form3.js

//************************************************
// File:    Form3.js (WSH sample in JScript) 
// Author:  (c) G. Born
//
// Using Internet Explorer 4 or 5 to retrieve
// form input
//************************************************

var vbOKOnly = 0;            // Pop-up dialog box VB constants
var vbInformation = 64;
var vbSystemModal = 4096;

var Title = "WSH sample form input - by G. Born";
var Text2 = "You entered:\n";

// *** Launch Internet Explorer. ***
var oIE = WScript.CreateObject("InternetExplorer.Application");
oIE.left=50;            // Window position
oIE.top = 100;          // and other properties
oIE.height = 380;
oIE.width = 450;
oIE.menubar = 0;        // No menu
oIE.toolbar = 0;
oIE.statusbar = 0;
oIE.navigate (GetPath() + "Form3.htm");  // Form
oIE.visible = 1;        // Keep visible

// Important: wait until Internet Explorer is ready.
while (oIE.Busy) {WScript.Sleep(200);}

// Try to initialize the text box value from the script.
oIE.Document.ValidForm.fRemark.value = "No remarks";
   
// Wait until the user clicks the OK button.
// Use the CheckVal function.
try
{
    while (oIE.Document.Script.CheckVal()==0)
        {WScript.Sleep(200);}  // Wait.
}

catch (e)
{
    WScript.Echo("Sorry, a run-time error occurred while checking" +
                 " the OK button \n" +
                 "I guess the form was closed; no input values...");
    WScript.Quit();        // End script
}
// User has clicked the OK button; retrieve the values.
name = "Name: " + oIE.Document.ValidForm.fName.value;
age = "Age: " + oIE.Document.ValidForm.fAge.value;
password = "Password: " + oIE.Document.ValidForm.fPassw.value;
printer = "Printer: " + oIE.Document.ValidForm.fPrinter.value +
          " Status: " + oIE.Document.ValidForm.fPrinter.checked;
screen = "Screen: " + oIE.Document.ValidForm.fScreen.value + 
         " Status: " + oIE.Document.ValidForm.fScreen.checked;
remark = "Remarks: " + oIE.Document.ValidForm.fRemark.value;

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Popup (Text2 + "\n" + name + "\n"+ age + "\n" +
                "\n" + password + "\n" + printer + "\n" +
                screen + "\n" + remark,0, Title, 
                vbOKOnly + vbInformation + vbSystemModal);

oIE.Quit();            // Close Internet Explorer.

function GetPath ()
{
    // Retrieve the script path.
    var path = WScript.ScriptFullName;  // Script name
    path = path.substr(0, path.lastIndexOf("\\") + 1);
    return path;
}

//*** End

You now know about the basic techniques for extending WSH scripts with a user interface. In Advanced Development with Microsoft Windows Script Host 2.0, I'll extend this technology with ActiveX forms (a topic beyond the scope of this book). I'll also show you how to use progress bars, bar graphs, and so on from scripts.