Windows脚本编程核心技术精解Chapter19.pdf
Chapter 19Using the WebBrowser ControlIn This Chapter?Discover the versatile WebBrowsercontrol,and create your own dialog boxesusing plain HTML templates?Enumerate and access DHTML elements?Link script procedures to DHTML buttons using GetRef,and bypass InternetExplorer security dialogs?Control your WebBrowserform window through HTML commands?Validate HTML form input,and color-code missing form fields?Let your COM object respond to events fired by the WebBrowsercontrol,and disable the context menu this way?Use radio buttons and determine which radio button was selected?Customize your HTML dialog container,change caption text,and disablesizingThe WebBrowsercontrol is the heart of Internet Explorer.It candisplay HTML documents and is a very versatile design element youcan incorporate into your own dialog boxes.In this chapter,learn howto use the WebBrowsercontrol to create fully configurable HTML-basedcustom dialog boxes and transfer the results back into your scripts.The WebBrowser Control:Mastering Real-World TasksMicrosoft has stuffed all kinds of controls into Windows,and while most s of them are busy working for the operating system,your scripts can accessthose components,too.One of the most versatile controls is the WebBrowsercontrol.It works insideof any Internet Explorer window,and because Microsoft keeps expanding therole HTML plays,youll see this control in many Windows 2000 system dialogboxes,too.The WebBrowsercontrol is actually a miniature Web browser.It containseverything necessary to load and display HTML content.4684-8 ch19.f.qc 3/3/00 9:42 AM Page 539Actually,Internet Explorer is just a wrapping around the WebBrowsercontrol.The Internet Explorer application provides the toolbars and other gadgetshelpful to navigate the Web,but the true power comes from the WebBrowsercontrol embedded in Internet Explorer.The WebBrowsercontrol is by no means limited to displaying Web pages.InChapter 5,I showed you how to use Internet Explorer as a versatile ScriptingHost output window.Now its time to take a close look at the real heart ofInternet Explorer.The WebBrowsercontrol is the perfect foundation for trulycustomizable dialog boxes.It makes much more sense to use the WebBrowsercontrol directly instead of accessing it through Internet Explorer and payingthe price for all of the overhead involved.Creating custom dialog boxesTheres a definite need for custom dialog boxes.The built-in set of dialogboxes accessible to the Scripting Host is very limited,and its impractical to create COM objects for any custom dialog box you may need.A much more versatile approach are HTML dialog boxes.You can createthem with your favorite HTML editor in a matter of minutes,and its easy to design these dialog boxes just as you can design a Web page.All you need is a way to display your HTML dialog boxes.Displaying is easyjust feed the HTML template to the WebBrowsercontrol.In addition,youllneed some extra tricks to be able to retrieve the results typed into your dialog box.Ive designed a COM object that uses the WebBrowsercontrol and includesmany fascinating tricks for interacting with the user.Install the COM objectinstallwebdialogsetup.exe.Full source code is provided atcomponentswebdialogwebdialog.vbp.Designing your form:Creating an HTML templateThe first thing needed is an HTML template.This template defines theelements of your dialog box.Heres a simple example.Type it into yourfavorite text editor and save it as TEMPLATE.HTMin the same folder you are going to use for the sample scripts:p font:12pt ArialYour name:540Part V:Accessing Hidden ComponentsII4684-8 ch19.f.qc 3/3/00 9:43 AM Page 540Next,open the template file.Internet Explorer displays the form,and you cancheck whether everything looks the way you planned.Displaying the template dialog boxNow you are ready to display the form template with your new custom dialogCOM object(see Figure 19-1).Make sure the following sample script is stored in the same folder you storedyour HTML template!19-1.VBSset tool=CreateObject(“Web.dialog”)current pathmyname=WScript.ScriptFullNamecp=left(myname,InstrRev(myname,“”)templatetemplate=cp&“template.htm”size dialogtool.Width=400tool.Height=300tool.Title=“My Form”tool.SetIcon“shell32.dll”,3tool.Resizable=true display dialog and return object referenceset webcontrol=tool.ShowDialog(template)MsgBox TypeName(webcontrol)Figure 19-1:Use an HTML template to design your own dialog box.The script creates a dialog box and displays your HTML template.Once youclick OK,the COM object returns a reference to the element collection.Youllneed this reference in a minute.First,take a look at your options in Table 19-1.Chapter 19:Using the WebBrowser Control541II4684-8 ch19.f.qc 3/3/00 9:43 AM Page 541Table 19-1Properties and Methods to Control the WebBrowser Dialog BoxMethod/PropertyDescriptionProperty CancelButton As StringCaption name of Cancel button.Function DisplayDialog As ObjectShows dialog box and returnselement collection.Property Height As LongHeight of dialog box in pixels.Function LoadDialog(ByVal template Loads dialog template and returns As String)As Objectelement collection.Property OKButton As StringCaption name of OK button.Property Resizable As BooleanTrue:Dialog box is resizable.Sub SetIcon(ByVal iconlib Sets the dialog box icon.Supply As String,ByVal index As Long)name of icon file and icon index.Sub ShowButtons(ByVal mode True:Dialog box displays OK and As Boolean)Cancel buttons.Function ShowDialog(ByVal template Combines LoadDialogand As String)As ObjectShowDialog:Loads a templatefile,displays the dialog box,andreturns element collection.Property Title As StringTitle of dialog box.Property Width As LongWidth of dialog box in pixels.Getting access to template elementsDisplaying your HTML template alone wont be enough.You need a way to accessthe elements in your HTML template in order to query their values.After all,youwant to know what the user has entered into your form(see Figure 19-2).Figure 19-2:Examine the elements accessible in your HTML template.542Part V:Accessing Hidden ComponentsII4684-8 ch19.f.qc 3/3/00 9:43 AM Page 542The COM object returns a reference to the element collection.This collectioncontains references to all the elements you placed onto your HTML page.Lets check out how to read this collection:19-2.VBSset tool=CreateObject(“Web.dialog”)current pathmyname=WScript.ScriptFullNamecp=left(myname,InstrRev(myname,“”)templatetemplate=cp&“template.htm”size dialogtool.Resizable=truetool.Width=400tool.Height=300tool.Title=“My Form”tool.SetIcon“shell32.dll”,3 display dialog and return object referenceset webcontrol=tool.ShowDialog(template)read all named elementsfor each element in webcontrolon error resume nextelname=element.nameif not err.number=0 then element has no name tag!elname=“no name property,type:“&TypeName(element)end ifon error goto 0list=list&elname&vbCrnextMsgBox listThis time,once you click OK,the script returns a list of all the elementsinside your HTML template.There are a lot of unnamed control elements,but you also see all the named elements.Named elements are elements you assigned a NAME=tag.Now its easy to retrieve the results someone has entered into your form:19-3.VBSset tool=CreateObject(“Web.dialog”)current pathmyname=WScript.ScriptFullNamecp=left(myname,InstrRev(myname,“”)Chapter 19:Using the WebBrowser Control543II4684-8 ch19.f.qc 3/3/00 9:43 AM Page 543 templatetemplate=cp&“template.htm”size dialogtool.Resizable=truetool.Width=400tool.Height=300tool.Title=“My Form”tool.SetIcon“shell32.dll”,3 display dialog and return object referenceset webcontrol=tool.ShowDialog(template)read inputif TypeName(webcontrol)=”Nothing”thenMsgBox“You cancelled!”elseMsgBox“You entered:“&webcontrol.namefield.valueend ifExpand your HTML template to ask for more than one piece of information.Its completely up to you how complex you want your dialog window to get!Figure 19-3:It worksyour script retrieves the input.Designing dialog box templatesThe most obvious advantage of HTML dialog boxes is their versatility.Youcan change the design of your dialog box templates without having to changethe COM object in any way,and you dont need any complicated subclassingtechniques to dynamically add or remove form elements.Theres only onething you need to ensure,and thats to supply a NAME=tagfor each inputelement you want to query.Without the NAME=property,your script cantaccess the elements value.Also take a look at the BODYtag.This tag defines the background color andturns off the vertical scroll bar.544Part V:Accessing Hidden ComponentsII4684-8 ch19.f.qc 3/3/00 9:43 AM Page 544The STYLEsection uses a style sheet to change the font the Pelement uses.Style sheets are a great way to globally assign formatting information to yourform elements.Revealing implementation detailsBefore I show you more tricks you can do with your new HTML dialog boxtool,here are some implementation details.If you dont care how the COMobject does its work,skip this part!The Resizableproperty is one of the most remarkable features:This propertycontrols whether or not your form window is resizable.This may not seem tobe a big deal,but actually it is.You cant change properties like this one duringrun-time.The window framewhich determines whether the form is resizableor notneeds to be defined at design-time.There are ways to overcome this limitation,but they are very complex.TheCOM object uses a much simpler approach.It actually uses two formsoneis resizable,and the other one isnt.The Resizable property sets a globalreference to one of the two forms,and all other properties and methods usethis reference.This is why you should use the Resizableproperty beforeyou use any of the other properties and methods.Generally,your dialog box is centered onscreen.Again,there are many complexways to center a form,but they are completely unnecessary.The form containsa property called StartUpPosition,and this property just needs to be set toCenterScreen.Thats all there is to it.The VBScript has some interesting parts,too!It uses ScriptFullNametoretrieve its own file path and extracts the pure path information.This way,the script“knows”the folder name it is stored in.This folder is appended tothe template filename,and as a result,you dont need to fiddle around withtemplate file paths.Just make sure the template file is stored in the samefolder you stored your script in.Advanced WebBrowser TricksLets take a quick look at the architecture of your HTML dialog boxes.Threecomponents are involved.Your script is part one.It launches the COM object,which in turn displays the WebBrowsercontrol.This is part two.Part three isyour HTML template,shown inside the WebBrowsercontrol.To get the most out of this architecture,you need ways to communicatebetween these components.Communication requires handles to the parti-cipating objects,and in the preceding examples,you saw how this works.CreateObjectreturns a handle to the COM object so your script can call itsinternal methods.ShowDialogin turn again returns a handle.To be exact,itreturns an element collection,and this element collection contains theChapter 19:Using the WebBrowser Control545II4684-8 ch19.f.qc 3/3/00 9:43 AM Page 545handles of all the elements inside your HTML template.Both your script andyour COM object can access any single HTML element in your template,andthe example used this handle to retrieve the value entered into the text field.Calling script procedures through your HTML templateMaybe you noticed the Help button on the sample form.It was of no useclicking the button didnt do a thing.Not yet,anyway.Test your new knowledge about inter-componentcommunications and hook up a script procedure to this button(see Figure 19-4).Your script needs to access the button.Thats easy,because your scriptknows the elements reference so it can access all properties.How can yourscript ask the button to execute a script procedure?Your script needs to geta reference to the script procedure and pass it to the onclickevent of thebutton.Sounds complicated,but it isnt!19-4.VBSset tool=CreateObject(“Web.dialog”)current pathmyname=WScript.ScriptFullNamecp=left(myname,InstrRev(myname,“”)templatetemplate=cp&“template.htm”size dialogtool.Width=400tool.Height=300tool.Title=“My Form”load template first!This way,you get a handle to the HTML elements without displaying the form yetset webcontrol=tool.LoadDialog(template)configure the dialog hook up a script procedure to the help buttonwebcontrol.help.onclick=GetRef(“showhelp”)now display the dialog.Note that the help button now invokes the showhelp procedure!set webcontrol=tool.DisplayDialog read inputif TypeName(webcontrol)=”Nothing”thenMsgBox“You cancelled!”546Part V:Accessing Hidden ComponentsII4684-8 ch19.f.qc 3/3/00 9:43 AM Page 546elseMsgBox“You entered:“&webcontrol.namefield.valueend ifsub ShowHelpMsgBox“Please enter your full name!”end subNow it works!Every time you click the Help button,a help message appears.This help message comes from your script.The help button remotely invokesthe ShowHelpprocedure defined in your script.You now can call any scriptprocedure while the dialog box is still visible.Imagine the possibilitiesnotonly can you supply Help buttons for any input field,you can also updateform elements through a database,or you can check the form contentsbefore you allow the user to quit the form.Figure 19-4:The Help button invokes the help procedure of your own script.The magic behind this is GetRef.This method returns a reference to the scriptprocedure,which in turn can be attached to the button onClickevent.Communication between the HTML templateand the COM objectSo far,your script has communicated with both the COM object and theHTML template elements.Is there a way your HTML template cancommunicate with the COM object,too?The COM object hosts your HTML template,and it can be nice to includebuttons in your template that control the COM object.For example,you caninclude a button that closes the dialog box.But how?Your HTML document needs a reference to your COM object.This is why the COM object tries to insert such a reference into your HTML document.hookquittries to assign the reference to a variable called parentobj.However,this fails because there is no such variable inside your HTMLdocument.Chapter 19:Using the WebBrowser Control547II4684-8 ch19.f.qc 3/3/00 9:43 AM Page 547But,you can change your HTML template.Open it inside a text editor andadd a script block.Then save it as TEMPLATE2.HTM:(see Figure 19-5)p font:12pt Arialset parentobj=Nothingsub Quitif not TypeName(parentobj)=”Nothing”thenparentobj.Quit falseend ifend subsub Leaveif not TypeName(parentobj)=”Nothing”thenparentobj.Quit trueend ifend subYour name:Now try your script again:Exchange TEMPLATE.HTMinside the script withTEMPLATE2.HTM,or use script 19-4-2.VBS.The form has changed,and thereare two more buttonsQuit and Done.Quit does exactly what your Formwindow Cancel button does,and Done mimics the OK button.Figure 19-5:You new tem