|
|
This chapter examines some of the major objects in the Word object model, starting with the Application object. Many of the objects in the Word object model are very large, and it is beyond the scope of this book to describe these objects completely. Instead, this discussion focuses on the most commonly used methods and properties associated with these objects. This chapter describes these objects as defined by the primary interop assemblies (PIAs) for Word. You should be aware that VSTO extends some of these objects (Document, Bookmark, XMLNodes, and XMLNode) to add some functionality, such as data binding support. Part III of this book, starting with Chapter 13, "The VSTO Programming Model," covers those extensions. The Application object is the largest object in the Word object model. The Application object is also the root object in the Word object model hierarchy. You can access all the other objects in the object model by starting at the Application object and accessing its properties and the properties of the objects it returns. The Application object also has a number of application-level settings that prove useful when automating Word. Controlling Word's Screen Updating BehaviorWhen your code is performing a set of changes to a document, you might want to set the Application object's ScreenUpdating property to False to prevent Word from updating the screen while your code runs. Turning off screen updating can also improve the performance of a long operation. Setting the property back to true refreshes the screen and allows Word to continue updating the screen. When changing an application-level property such as ScreenUpdating, always save the value of the property before you change it, and set it back to that value when you have finished. Doing so is important because your code will almost never be running by itself inside the Word process; it will usually run alongside other code loaded into the Word process. Another add-in might be running a long operation on the document, for example, and that add-in might have set the ScreenUpdating property to False to accelerate that operation. That add-in might change the document in some way that triggers an event handled by your code. If your event handler sets the ScreenUpdating property to False and then sets it back to true when you have finished, you have defeated the add-in's attempt to accelerate its own long operation. If instead you save the value of ScreenUpdating before you change it, set ScreenUpdating to False, and then set ScreenUpdating back to its original value, your code will coexist better with other code running inside Word. The best way to do this is to use Visual Basic's support for exception handling to ensure that even if an exception occurs in your code, the application-level property you are changing will be set back to its original value. You should put the code to set the application-level property back to its original value in a Finally block because this code will run both when no exception occurs and when an exception occurs. Listing 8.1 shows an example of saving the state of the ScreenUpdating property, setting the property to False, and then restoring the original value of the property in a Finally block. Listing 8.1. A VSTO Customization That Uses the ScreenUpdating Property
In addition to the ScreenUpdating property, Word's Application object has a ScreenRefresh method. You can call this method to force a refresh of the screentypically, during an operation when you have set ScreenUpdating to False. You might do the first few steps of an operation, for example, refresh the screen to show the user the new state of the document, perform additional steps, and refresh the screen again. Controlling the Dialog Boxes and Alerts That Word DisplaysOccasionally, the code you write will cause Word to display dialog boxes prompting the user to make a decision or alerting the user that something is about to occur. If you find this happening in a section of your code, you might want to prevent these dialog boxes from being displayed so that your code can run without requiring intervention from the user. You can set the DisplayAlerts property to a member of the WdAlertLevel enumeration. If set to wdAlertsNone, this prevents Word from displaying dialog boxes and messages when your code is running and causes Word to choose the default response to any dialog boxes or messages that might display. You can also set the property to wdAlertsMessageBox to let Word display only message boxes and not alerts. Setting the property to wdAlertsAll restores Word's default behavior. Be sure to get the original value of this property, and set the property back to its original value after your code runs. Use try and Finally blocks to ensure that you set the property back to its original value even when an exception occurs. Changing the Mouse PointerDuring a long operation, you might want to change the appearance of Word's mouse pointer to an hourglass to let users know that they are waiting for some operation to complete. Word's Application object has a System property that returns a System object. The System object has a Cursor property of type WdCursorType that enables you to change the appearance of Word's mouse pointer. You can set it to the following values: wdCursorIBeam, wdCursorNormal, wdCursorNorthwestArrow, or wdCursorWait. Listing 8.2 shows the use of the Cursor property. Listing 8.2. A VSTO Customization That Sets the Cursor Property
Displaying a Message in Word's Status Bar or Window CaptionWord lets you set a custom message in the Word status bar, which is at the bottom-left corner of Word's window. StatusBar is a property that can be set to a String value representing the message you want to display in Word's status bar. Unlike most of the other properties in this section, you cannot save the original value of the StatusBar property and set it back after you have changed it. StatusBar is a write-only property and cannot be read. You can control the text shown in Word's window caption using the Caption property. Caption is a property that can be set to a String value representing the text you want to display in Word's window caption. Listing 8.3 shows an example of setting the StatusBar property to inform the user of the progress of a long operation. The operation has 1,000 steps, and after every 100 steps, the code appends an additional period (.) to the status-bar message to indicate to the user that the operation is still in progress. Listing 8.3. A VSTO Customization That Sets the StatusBar Property
Controlling the Look of WordWord enables you to control the Word user interface through other properties, such as those listed in Table 8.1. Listing 8.4 shows code behind a VSTO Word document that sets many of these properties.
Listing 8.4. A VSTO Customization and Helper Function That Modifies the Word User Interface
Properties That Return Active or Selected ObjectsThe Application object has a number of properties that return active objectsobjects representing things that are active or selected within Word. Table 8.2 shows some of these properties. Listing 8.5 shows code behind a VSTO Word document that examines these properties.
Listing 8.5. A VSTO Customization and Helper Function That Examines Active Objects
Properties That Return Important CollectionsThe Application object has a number of properties that return collections you will use frequently. Table 8.3 shows several of these properties. Listing 8.6 shows code behind a VSTO Word document that gets the count of these collections and the first item out of each collection.
Listing 8.6. A VSTO Customization and Helper Function That Examines Collections
Navigating a DocumentThe Browser property returns the Browser object, which gives you access to the same functionality available in the browser control that is shown directly below Word's vertical scroll bar, as shown in Figure 8.1. Figure 8.1. Word's browser control.
To use the Browser object, first set the Browser object's Target property to a member of the WdBrowseTarget enumeration, as shown here:
Then use the Browser object's Next and Previous methods to navigate from element to element. Listing 8.7 shows an example of this. Listing 8.7. A VSTO Customization That Uses the Browser Object
Note that using this approach also changes the selection in the document, which you often do not want to do. Later in this chapter, you learn about the Range object and the various ways you manipulate text with the Range object without changing the selection. The Range object's Goto, GotoNext, and GotoPrevious methods provide the same kind of navigation control that the Browser object provides, without changing the selection. Working with Word's OptionsThe Options property provides access to options you might set via the Options dialog box. The Options property returns an Options object that has more than 200 properties you can set. Listing 8.8 shows an example that gets and then prompts the user to decide whether to change several of the properties on the Options object. The properties set are options from the Save tab of Word's Options dialog box. Listing 8.8 also shows the Save tab in the Options dialog box after prompting the user to change options associated with that tab. Listing 8.8. A VSTO Customization That Uses the Options Object and Shows a Built-In Dialog Box
Working with the New and Getting Started Document Task PanesThe NewDocument property returns a NewFile object that lets you customize the New Document and Getting Started task panes. The NewFile object is a shared object in the office.dll PIA that defines types in the Microsoft.Office.Core namespace. The NewFile object is also used by Excel because it shares the same task-pane infrastructure. To get to the NewFile object in Excel, use the Excel Application object's NewWorkbook property. In four sections of the New Document task pane, you can add your own documents, templates, or Web addresses. These four sections are the New section, the Templates section, the Recently Used Templates section, and the Other Files section. Figure 8.2 shows the New Document task pane and these four sections. You can also add your own document, template, or Web address to the Open section of the Getting Started task pane. Figure 8.2. The New Document task pane.
The NewDocument property returns a NewFile object that has two methods of interest: Add and Remove. These methods take a filename as a String, a member of the Office.MsoFileNewSection enumeration to specify the section you want to add or remove from, the display name as a String that you want displayed in the task pane, and the action to take when the user clicks the link in the task pane. The action is specified using a member of the Office.MsoFileNewAction enumeration. Possible actions include msoOpenFile, which opens the document or URL using Internet Explorer; msoCreateNewFile, which creates a new document based on the existing document or template; and msoEditFile, which opens an existing document for editing in Word. Listing 8.9 shows some code that adds a document or hyperlink to each of the four sections in the New Document task pane. It also adds a document to the Getting Started task pane. To show the New Document task pane, the code uses an unusual technique: It finds the command bar control for the File > New command (which has an ID of 18) and executes that command. This is done because the New Document task pane cannot be shown in any other way; it is not accessible through the TaskPanes object, as you would expect. The code in Listing 8.9 also handles the Document object's BeforeClose event to remove the added commands from the task pane. As you see in Chapter 7, "Working with Word Events," the BeforeClose event can be raised multiple times for the same document if the user cancels the save or closing of the document or if other BeforeClose event handlers cancel the close. In this case, even if the code in the BeforeClose event runs multiple times, the calls to NewFile.Remove do not raise any exceptions if the item you are trying to remove does not exist. Listing 8.9. A VSTO Customization That Adds Links to the New Document Task Pane
Working with the File Save Format OptionsThe DefaultSaveFormat property enables you to change the default format that Word saves in when the user creates a new document and then saves it. Setting DefaultSaveFormat to "Text" will cause Word to save new files in text-only format; for example, setting DefaultSaveFormat to an empty string will cause Word to save in the default file format. You can also specify that one of the installed file converters be used as the default save format. The FileConverters property returns a collection of available file converters that save in formats such as Works format. Each FileConverter object in the FileConverters collection has a ClassName property that returns a String. You can set the DefaultSaveFormat property to the String returned by the ClassName property of the FileConverter you want to use as the default save format. The Works 6.0 & 7.0 FileConverter object has a ClassName property that returns "wks632". Setting DefaultSaveFormat to "wks632" will make Works 6.0 & 7.0 the default save format. Working with File Dialog BoxesWord provides several properties and methods that enable you to change the directory that the Open and Save dialog boxes default to. The ChangeFileOpenDirectory method takes a String parameter that is the new path that you want the Open and Save dialog boxes to default to. A change made using this method lasts only until the user exits the application or ChangeFileOpenDirectory is called again during the run of the application. To change permanently the directory that the Open and Save dialog boxes default to, you can use the Options object's DefaultFilePath property. Prompt the user if you change a setting like this permanently. Users usually do not appreciate it when programs change their settings without asking their permission first. If you need to display a customized File dialog box, you can use the FileDialog property, which returns a FileDialog object you can customize and show to the user. The FileDialog property takes a required parameter of type Office.MsoFileDialogType, which can be one of the following enumerated values: msoFileDialogOpen, msoFileDialogSaveAs, msoFileDialogFilePicker, or msoFileDialogFolderPicker. Listing 8.10 shows an example that gets a FileDialog of type msoFileDialogFilePicker and modifies it to let the user select files from the desktop to copy to his C:\ directory. There are several things to observe in this example. First, the FileDialog object has several properties that enable you to customize the dialog box, including AllowMultiSelect, ButtonName, InitialFileName, InitialView, and Title. Listing 8.10 also illustrates that showing the FileDialog using the Show method does not perform any Word action, such as opening files, when the user clicks the default button. Instead, it returns an Integer value that is 1 if the user clicked the default button and 0 if the user clicked the Cancel button. If the user clicks the default button, and Show returns a 1, the code iterates over the FileDialog's SelectedItems collection to get the files that the user selected to copy. Listing 8.10. A VSTO Customization That Modifies Word's File Dialog Box
User InformationWord's Application object has several properties that return user information, including UserName, UserAddress, and UserInitials. These String properties return the user information the user entered when installing the product. The user can also edit this information by going to Word's Options dialog box and editing the fields in the User Information tab. Checking Grammar and SpellingWord provides some application-level methods that enable you to use Word's grammar and spelling engine to check arbitrary strings. CheckGrammar is a method that takes a String and returns a Boolean value. It returns true if the string is deemed grammatically correct by Word's grammar checker and False if it is not. CheckSpelling is a method that takes a String and returns true if the string is spelled correctly and False if the string is not spelled correctly. The GetSpellingSuggestions method can take a single word that is misspelled and suggest possible correct spellings for the word. It takes a required String that is the word to check. It also takes a number of optional parameters. It returns a SpellingSuggestions collection that contains possible correct spellings. Listing 8.11 shows a VSTO customization that uses these application-level grammar and spelling-checking functions. Listing 8.11. A VSTO Customization That Checks Grammar and Spelling
Exiting WordThe Quit method can be used to exit Word. If any unsaved documents are open, Word prompts the user to save each unsaved document. When users are prompted to save, they get a dialog box that has a Cancel button. If the user clicks Cancel, or if any code is running that is handling the Application.DocumentBeforeClose event sets the cancel parameter to true, Word does not quit. Setting the DisplayAlerts property to wdAlertsNone will not suppress Word's prompting the user to save. Fortunately, the Quit method takes three optional parameters that can control whether Word prompts the user to save. The first optional parameter, called SaveChanges, is of type Object and can be passed a member of the WdSaveOptions enumeration: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges. The second optional parameter, called OriginalFormat, is of type Object and can be passed a member of the WdOriginalFormat enumeration: wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument. This parameter controls Word's behavior when saving a changed document whose original format was not Word document format. The final optional parameter is called RouteDocument and is of type Object. Passing true for this parameter routes the document to the next recipient if a routing slip is attached. Listing 8.12 shows a VSTO application that calls Quit without saving changes. Listing 8.12. A VSTO Customization That Calls Quit
|
|
|