Schongar P.VBScript unleashed.1997
.pdfimages to display, you could end up being better off to start up an ActiveMovie control and stream the images as AVI, controlling their playback rate. It's all a matter of give and take.
Divide and Conquer
Remember that speed on the Internet is relative to the amount of data that must be sent over your network connection. The fastest code in the Internet is the code that makes it from your Internet service provider to your local machine in the shortest time. Deadly wait times while a program is downloading can make an early end of an ambitious project. It may actually be a good idea to divide your application into smaller segments and have the user navigate between HTML pages. This keeps the download time at a minimum between parts of your application and will give the best response time to your users who only have 14.4 modem connections. Because VBScript programming and HTML code is realistically just pages and pages of text, the less text you have to transfer, the faster your application will be downloaded to the local machine and processed. Try to keep your applications as tight as possible without giving up your standards. Keep in mind that making your users navigate a little more to get where they are going can often be seen as a higher level of interactivity.
Development Tools
Creating interactive applications can be easy or hard, depending on the tools you have available to you. Developing with VBScript and ActiveX was, like anything else, not a walk in the park when it first came out. But even just a few months after you catch on, a number of options exist for you to get the job done.
Still Using a Text Editor?
Okay, there are a lot of us out there who just refuse to "modernize" certain aspects of our development process. I'll admit to being one of them when it comes to things like HTML page creation, and wanting to do HTML coding all "by hand," instead of relying on someone else's stab at what everyone wants in an HTML editor. If you know the syntax, and type pretty fast, your run-of-the-mill text editor (like Notepad, the old standby) can crank out some useful stuff pretty quickly, and on any system you choose. No quirky development environments, costs, or cryptic interfaces... just you and a heck of a lot of text.
ActiveX Control Pad
While the romance and mystique of the text-editor-using code-creating guru may be something you want to continue to inspire in public, don't be too resistant to certain changes. Advanced interactions, such as those between VBScript and ActiveX controls, require the entry of dozens of parameters and incredibly weird sequences of numbers, which you really don't want to try to memorize, do you? Microsoft likes to call them Globally Unique Identifiers (GUIDs), but you can just call them a pain to type in.
Each ActiveX control has a GUID in the form of a ClassID, which tells the client system a lot of things about the control and allows the system to check and see if it has it on hand. If you're up to the task of memorizing 32-bit numbers for every control you plan on integrating, and you would rather type those sequences by hand every time you use each control, you can consider yourself a pretty die-hard ASCII editor fan. You'd also be very wealthy if you got paid by the hour for that.
The next rung up the evolutionary ladder of coding is the ActiveX Control Pad. While not really an Integrated Development Environment (IDE), it does take the first step toward making development easier, and the Control Pad is free. Both of those weigh heavily in its favor, no matter what kind of quirks or drawbacks people may associate with its use.
The Control Pad provides a toolbox for putting together the most commonly used pieces of your HTML page. Objects, properties, positioning... they're all there for your benefit, if you're willing to give it a try. If you don't know the ClassIDs of the objects you were planning to use, it cuts the time even more significantly. By the time you hunt
through and look up the ClassID for use with a text editor, you could have placed three distinct classes of objects on your page with Control Pad.
Visual Basic to VBScript Converters
Going even further in optimizing your development time, you can take an existing Visual Basic application and convert it, or the majority of it, to VBScript. The first publicized tool of this sort, VBNet, came out at the time of this writing. It takes existing Visual Basic applications and converts them into VBScript-based applications instead-at least mostly.
There are two conflicting schools of thought when it comes to applications like this, because of one simple fact; since VBScript is a subset of a subset of Visual Basic running in a special environment, not all applications (and certainly not all functionality) can transfer from the original application. On one hand this leaves developers saying, "Well, if it can't handle my specific function, then what good is it?" But on the other hand, it makes a large number of other developers smile because it does at least some of the work for them.
The most important thing to do when considering conversion is to take a long, hard look at the original application, and see what kind of functions it needs. File I/O and a pile of other common functions will either end up requiring links to a server-side CGI program or the use of ActiveX controls. Remembering the earlier discussion on download times and the number of controls being used, this could be a problem.
For the moment, treat Visual Basic to VBScript converters as a good step to getting rid of the basic time-consuming steps, but definitely short of a fully optimized and fully functional porting tool. There's no doubt that the tools that currently exist will improve, and that future tools will continue to fuel the competition for the most effective converter on the market. But don't bet the farm on the perfect tool... be prepared to do some of the conversion tune-up yourself.
Future Integrated Development Environments?
Is there a real Integrated Development Environment in VBScript's future? Considering the market that Microsoft is trying to push VBScript into, the sheer number of possible users would seem to be too lucrative for some developers to pass up. As other applications and corporations decide whether to begin hosting VBScript in their applications, each may end up with its own special integration and specialty interfaces.
With Visual Basic 5.0, Visual Basic for Applications, and VBScript to consider, Microsoft may well end up turning Visual Basic into an all-purpose IDE that could use a project wizard to make anything from a full-blown Visual Basic application all the way down to the simplest of VBScript functions. Embedding a Visual Basic/VBA to VBScript converter wouldn't be a bad thing either, considering that they would have an instant inventory of what ActiveX controls were available to provide necessary functionality. While VBScript may be free to the public, rest assured that Microsoft will certainly aim to make a profit from related components, as will countless other developers.
Review
The right amount of optimization is the amount that feels comfortable to you. You don't want to spend all your time tweaking something when there won't be any discernible improvement, but you shouldn't leave code up that could be significantly improved. Since your VBScript source code is there for the world to see, it's their first indication of your work, and they get to see it all, from the organization to the finished results. You only get one chance to make a first impression.
As you begin to integrate more advanced functionality, make sure that you standardize as much as possible. If you have ever worked in a workgroup environment, you know what it is like to look at someone else's code and have absolutely no idea how they got where they are going. A good set of rules set at the beginning of a project and followed through to completion will get your work out the door faster and make your code reusable. There may not be much that you can do to increase VBScript performance-wise, but the performance of your application can be greatly dependent on how it is maintained and reused. A lot of unnecessary hacking into a program to fix undocumented problems will definitely cut back the efficiency of your work.
Chapter 26
RTFEditor
by Evangelos Petroutsos
CONTENTS
Using OCX Controls with VBScript
The RTFEditor Application
The Rich Textbox Control
Designing the User Interface
The Code Behind the Scenes
Saving and Recalling RTF Documents
Review
Using OCX Controls with VBScript
You've seen examples of ActiveX controls, which were designed specifically for VBScript and Web applications. Controls are not new to the Windows environment, though. They are the basic building blocks of the Windows user interface and as such existed long before VBScript, and were called OCX controls. If you have programmed in the Windows environment, you are familiar with OCX controls. ActiveX is a new specification for building controls that can be used both on the desktop and within a browser. Eventually, all the existing OCX controls will be converted to ActiveX format and you'll be able to use them on your Web pages or desktop applications written in most languages, like Visual Basic or Visual C++. As of this writing, however, there aren't many ActiveX controls. Over the next year, numerous ActiveX controls will become available from Microsoft and other companies. They will be more flexible than the existing ones, and you'll find in them all the functionality you want to incorporate into your VBScript applications.
This chapter covers some of the old OCX controls in Web page design. OCX controls aren't meant to be used with VBScript, but they work and you'll get a good idea of the kind of functionality they can add to your applications. To follow the examples of this and the following chapter, you must have certain OCX controls installed on your system. Windows programming languages, such as Visual Basic and Visual C++, will automatically install these OCX controls on your system. If you don't have one of these programming tools installed on your system, you should wait for the ActiveX versions of these controls or consider purchasing Visual Basic. The upcoming version of Visual Basic (version 5.0) will be an ideal complement to VBScript. You should also check Microsoft's Workshop site (www.microsoft. com/workshop) for new ActiveX controls and updates.
The RTFEditor Application
The first OCX control discussed is the Rich Textbox control. The Rich Textbox control is in a small but very flexible word processor that combines the functionality of a Textbox control with formatting capabilities. If you want the Textbox control to display multiple fonts and styles, the Rich Textbox control is what you need. The application we are going to build in this chapter is called RTFEditor, and you can find it in this chapter's folder on the CD-ROM. Apart from showing you how to use the Rich Textbox control to build a word processor, the RTFEditor application
demonstrates how to use command buttons and the Popup Menu control to build a user interface with menus. As long as HTML layouts can't have a menu structure of their own similar to the one you see on practically every Windows application, you'll have to use the Popup Menu control to creatively provide your users with the means to interact with your applications.
The RTFEditor application, shown in Figure 26.1, is a functional word processor that runs from within Internet Explorer's environment. Users can type text and edit it using the common editing operations (such as cut and paste) and the editing keys common to any text editing application in the Windows environment (like Home and Ctrl-C). In addition, they can use the menus behind the command buttons to format the text.
Figure 26.1 : RTFEditor is a functional word processing application that can be placed on a Web page and operated
from within Internet Explorer 3.0.
The command buttons at the bottom of the page act as triggers for popup menus, with the various formatting options. The popup menus that correspond to each command button are shown in Figure 26.2. We have included a few very basic formatting commands to demonstrate the capabilities of the Rich Textbox control, and you can add more formatting options on your own. Even with the basic functionality we've built into it, RTFEditor is a functional application that provides most of the functionality of a word processor needed by the average user on a daily basis.
Figure 26.2 : The options of the RTFEditor application's popup menus.
You can open the RTFEditor application and familiarize yourself with it. Every time the RTFEditor page is loaded, Internet Explorer 3.0 will issue a warning to the effect that the application contains controls that might not be safe for your system, shown in Figure 26.3. This warning means that the page contains controls that Internet Explorer can handle, but they are not ActiveX controls and have not been verified for safety on the Web. The controls we are going to use are common Windows controls, and you can safely put them on your pages; so click the Yes to All button to continue. You just have to live with the inconvenience of seeing this message every time the page is loaded.
Figure 26.3 : By default, Internet Explorer will warn you with this message box each time it's about to load a Web page
with an OCX control.
NOTE
You can bypass this warning through the safety settings of Internet Explorer, but we don't recommend changing the browser's settings while you surf the Web. If you follow the procedure outlined here, make sure you restore the original settings before you load other people's pages.
To change the safety level of Internet Explorer, open the Options dialog box by selecting Options from the View menu. Then click the Security tab and on the new page click Safety Level to bring up the Safety Level window of Figure 26.4.
Figure 26.4 : The Safety Level settings let you specify how Internet Explorer will handle potential security and safety
problems.
Click the None radio button and then click the OK button twice to close the Options dialog box. Now you can load the pages of this and the next chapter without the inconvenience of the warning of Figure 26.2.
You're now ready to look at the application. First, however, let's review the Rich Textbox control, its properties, and its
methods that we are going to use in the example.
The Rich Textbox Control
Let's start by looking at the various properties of the control that we'll use in building the RTFEditor application. The basic property of the Rich Textbox control is its RTFText property. RTF stands for rich text format and is a language for describing formatted documents, not unlike HTML. Like HTML, RTF was designed to create portable formatted documents that can be displayed on different systems. The RTF language uses tags to describe the document's format. For example, the tag for italics is \i, and its scope is delimited with the next character formatting tag (which in most cases is the \plain tag, which restores the text style to plain). The following RTF line will produce a sentence with a few words in italics:
RTF is a language for creating \i portable formatted\plain documents
The equivalent HTML code would be
RTF is a language for creating <I>portable formatted</I> documents
RTF, however, is much more complicated than HTML because RTF was meant to be used internally by applications. Just as you need a browser to view HTML documents, you need an RTF-capable application to view RTF documents. WordPad, for instance, supports RTF and can save a document in RTF format and read RTF files. But you're not expected to supply your own RTF code to produce a document.
To demonstrate the principles of RTF and how to create portable documents in RTF, let's create a simple formatted document with WordPad and then look at the source code. Start WordPad, enter some text, and format it any way you can with the program's tools. Figure 26.5 shows the same document contained in the Rich Textbox control of Figure 26.1, after it was copied from the RTFEditor application (with the Ctrl-C keystroke) and pasted into a Word document (with the Ctrl-V keystroke). The text was actually transferred in RTF format, which shows you that RTF is indeed a universal language, at least in the Windows environment. If you can exchange RTF files with other types of operating systems, you'll realize that RTF is indeed a universal file format for exchanging formatted files. You can also try to modify the text in Word, copy it, and paste it into the RTFEditor's window.
Figure 26.5 : The Rich Textbox control lets you exchange formatted documents with other Windows applications, like
Word.
Now you can save the text in RTF format too. Select the Save As command from the File menu, and in the dialog box that will be displayed on the screen select Rich Text Format. Then save the file as Document.rtf. (You don't have to supply the extension.) You can find the RTF code for the document of Figure 26.5 in the folder with this chapter's examples on the CD-ROM. If you open this file with a text editor (any application that can't interpret RTF code), you'll see the actual code that produced the document:
{\rtf1\ansi\deff0\deftab720{\fonttbl{\f4\fnil MS Sans Serif;}{\b\fnil \fcharset2 Symbol;}
{\b\ System;}{\f4\fnil Times New Roman;}{\f4\fnil\fprq2 Verdana;} {\f11\fnil\fprq2 Impact;}
{\f11\fnil\fprq2 Comic Sans MS;}}
{\colortbl\red0\green0\blue0;\red16\green16\blue255;\red255\green16
\blue16;}
\deflang1033\pard\qc\plain\f4\ RTFEditor Features\plain\f4\
\par \pard\plain\f4\
\par \plain\f4\ Character Formatting\plain\f4\ :
\par Regular, \plain\f4\ Bold\plain\f4\ , \plain\f4\ Italics,\plain \f4\
\plain\f4\ Underline\plain\f4\ and \plain\f4\ combinations
\par \plain\f4\
\par \plain\f4\ Paragraph Formatting\plain\f4\
\par Left aligned paragraphs
\par \pard\qc\plain\f4\ Centered paragraphs
\par \pard\qr\plain\f4\ Right aligned paragraphs
\par \pard\plain\f4\ Font and Sizes\plain\f4\
\par Mix \plain\f11\ various\plain\f4\ \plain\f11\ fonts\plain\f4\
and \plain\f4\ sizes\plain\f4\
\par \plain\f4\ Text\plain\f4\ \plain\f4\ and background colors \plain\f4\
\par \pard\plain\f4\
\par }
If you look carefully at the RTF code, you'll be able to see where the text and the formatting tags are. The \par tag inserts a paragraph similar to the <P> tag in HTML. The \bold tag delimits text to be displayed in bold. The file's header holds information about the fonts used in the document. The designation f4 corresponds to the Verdana font and appears quite frequently in the text.
The RTF format makes it possible to format text on a Rich Textbox control. But producing cryptic text as in the RTF code segment shown previously to display a few lines of formatted text isn't VBScript's way of doing things. Indeed, the Rich Textbox control simplifies this process by providing a number of properties for formatting the text.
Text Manipulation Properties
The Rich Textbox control has many properties, the most important of them being the ones that manipulate the selected text. All these properties start with the prefix Sel. SelText is the selected text. To assign the selected text to a variable, use the statement
SText=RichTextbox1.SelText
where RichTextbox1 is the name of the control. You can also modify the selected text by assigning a new value to the SelText property. The statement
RichTextbox1.SelText=UCase(RichTextbox1.SelText)
converts the selected text to uppercase. If you assign a string to the SelText property, the selected text in the control will be replaced. The statement
RichTextbox1.SelText="replacement string"
will replace the current selection on the RichTextbox1 control with the string "replacement string". If no text was selected, the same statement will insert the string at the location of the pointer. It is possible, therefore, to automatically insert text by assigning a string to the SelText property. This technique is quite useful in displaying some initial text on the control.
To simplify the manipulation and formatting of the text on the control, there are two additional properties, the SelStart and SelLength properties, which report the position of the first selected character in the text and the length of the selection respectively. You can also set the values of these properties to select a piece of text from within your code. One obvious use of these properties is to select (and highlight) the entire text:
RichTextBox1.SelStart=0
RichTextBox1.SelLength=Len(RichTextBox1.Text)
The Text property returns the text on the control, just like the Text property of the TextBox control.
Text Formatting Properties
The properties for formatting the selected text are SelBold, SelItalic, and SelUnderline. You can read the value of these properties to check the formatting of the selected text from within your code or set them to change the formatting accordingly. The statements
RichTextbox1.SelBold=True
RichTextbox1.SelItalic=True
turn on the bold and italic attributes of the selected text. Again, if no text is selected, the attributes are set for the character at the current location of the pointer. By setting the character formatting properties accordingly, the user is in effect changing the style of the text he or she is about to type.
The character formatting properties are used as toggles. Every time the user clicks the Bold button (or selects Bold from the application's menu), the following code is executed:
RichTextbox1.SelBold=NOT RichTextbox1.SelBold
If the selected text is in bold, it's turned back to normal; if it's normal, it's turned to bold. As you have noticed, there is no property to reset the text style back to normal. To do so, you must manually set all three properties to False:
RichTextbox1.SelBold=False
RichTextbox1.SelItalic=False
RichTextbox1.SelUnderline=False
The SelAlignment property lets you read or change the alignment of one or more paragraphs, and it can have one of the following values:
0(Default) Left aligns selected paragraph(s)
1Right aligns selected paragraph(s)
2Centers selected paragraph(s)
Notice that the user doesn't have to actually select the entire paragraph to be aligned. Placing the pointer anywhere on the paragraph to be reformatted or selecting a few characters in the paragraph will do, because there is no way to align part of the paragraph only.
To change the font and style of the selected text, use the properties SelFontName and SelFontSize. The following statements will render the selected text in Verdana font, 24 points:
RICHTEXT.SelFontName = "Verdana"
RICHTEXT.SelFontSize = 24
You must supply a font name that exists on the client computer, or a similar font will be substituted. As of now, it's not possible for VBScript to read the names of the fonts installed on the client computer and present them to the viewer to select one.
Finally, there are two properties for creating bulleted items: the SelBullet property-and controlling the text's baseline, the SelOffset property. If the SelBullet property is set to True, the selected paragraphs are formatted with a bullet style, similar to the UL tag in HTML. To create a list of bullet items, select them with the pointer and assign the value True to the SelBullet property. To restore a list of bullet items to normal text, select the items and assign the value False to the SelBullet property.
The SelOffset property determines whether the selected characters appear on, above, or below the normal text baseline. Normally, text appears on the baseline. You can raise its baseline to create superscripts (you must also reduce its size a point or two) or lower it to create subscripts. To lower the baseline of the selected text, assign a negative number to the SelOffset property. This value must be expressed in twips. (A twip corresponds to one-twentieth of a point, and there are 72 points in an inch.)
As you have realized, creating a functional, even fancy, word processor based on the Rich Textbox control is quite simple. You must provide a convenient user interface that lets the user select text and apply attributes and styles to it, and then set the control's properties accordingly. This is exactly what this chapter's application does.
Designing the User Interface
The RTFEditor's user interface is rather simple because VBScript doesn't provide the elaborate menu structures you need to build an application of this type. The commands for manipulating the text are placed in Popup Menu controls, which are activated by clicking the various command buttons below the Rich Textbox control. As usual, we'll start with the design of the layout and then look at the code.
To create the layout of Figure 26.1, create a new HTML document and place a Rich Textbox control on it with the Insert ActiveX control command of the Edit menu. When the Insert ActiveX Control window (shown in Figure 26.6) appears on the screen, locate the item Microsoft Rich Textbox Control and click the OK button.
Figure 26.6 : The Insert ActiveX Control window can be used to insert OCX controls on an HTML document.
Although it's possible to add this control to the Control Pad's toolbox and then draw a new control directly on the HTML layout, Internet Explorer will refuse to load the control at runtime. Instead, it will display the error message shown in Figure 26.7. This is a stubborn message you can't avoid no matter what your settings for safety and security are. The only way to avoid this message is to place the OCX control directly on the HTML document, with the Insert ActiveX Control command. When the application is loaded, you'll be warned that the document contains a control that may not be safe for your system, but it will at least give you the option to load the unsafe control.
Figure 26.7 : If you place a Rich Textbox control directly on a layout, Internet Explorer will refuse to load it.
When the Edit ActiveX Control window appears, adjust the size of the control and set the default font. You must also set its Scrollbars property to 2 (Vertical) or 3 (Both) so that the users will be able to quickly move to any location in a long document. After you have adjusted the size and the properties of the control, VBScript will insert an object definition like the following one in the HTML file:
<OBJECT ID="RichTextBox1" WIDTH=100 HEIGHT=51
CLASSID="CLSID:3B7C8860-D78F-101B-B9B5-04021C009402">
<PARAM NAME="_Version" VALUE="65536">
<PARAM NAME="_ExtentX" VALUE="2646">
<PARAM NAME="_ExtentY" VALUE="1323">
<PARAM NAME="_StockProps" VALUE="69">
<PARAM NAME="BackColor" VALUE="-2147483643">
<PARAM NAME="ScrollBars" VALUE="2">
<PARAM NAME="TextRTF" VALUE="{\rtf1\ansi\deff0\deftab720
{\fonttbl{\f4\fnil MS Sans Serif;}{\b\fnil\fcharset2 Symbol;} {\b\ System;}
{\f4\fnil\fprq2 MS Sans Serif;}}
{\colortbl\red0\green0\blue0;}
\deflang1033\pard\plain\f4\
