Working with the Application Object


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 Behavior

When 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

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim app As Word.Application = Me.Application     Dim oldScreenUpdateSetting As Boolean = app.ScreenUpdating     Dim range As Word.Range = Me.Range     Try       app.ScreenUpdating = False       Dim r As New Random()       Dim i As Integer       For i = 1 To 1000         range.Text = range.Text + r.NextDouble().ToString()         If i Mod 333 = 0 Then           app.ScreenRefresh()         End If       Next     Finally       app.ScreenUpdating = oldScreenUpdateSetting     End Try   End Sub End Class 


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 Displays

Occasionally, 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 Pointer

During 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

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) _     Handles Me.Startup     Dim app As Word.Application = Me.Application     Dim oldCursor As Word.WdCursorType = app.System.Cursor     Dim range As Word.Range = Me.Range     Try       app.System.Cursor = Word.WdCursorType.wdCursorWait       Dim r As Random = New Random()       Dim i As Integer       For i = 1 To 1000         range.Text = range.Text + r.NextDouble().ToString()       Next     Finally       app.System.Cursor = oldCursor     End Try   End Sub End Class 


Displaying a Message in Word's Status Bar or Window Caption

Word 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

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim app As Word.Application = Me.Application     Dim status As String = "Creating Document..."     app.StatusBar = status     Dim range As Word.Range = Me.Range     Try       app.System.Cursor = Word.WdCursorType.wdCursorWait       Dim r As Random = New Random()       Dim i As Integer       For i = 1 To 1000         range.Text = range.Text + r.NextDouble().ToString()         If i Mod 100 = 0 Then           status &= "."           app.StatusBar = status         End If       Next     Finally       app.StatusBar = String.Empty     End Try   End Sub End Class 


Controlling the Look of Word

Word 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.

Table 8.1. Properties That Control Elements of the Word User Interface

Property Name

Type

What It Does

DisplayAutoCompleteTips

Boolean

Controls whether Word displays autocomplete tips for completing words, phrases, and dates as you type.

DisplayRecentFiles

Boolean

Controls whether Word displays recently open files in the File menu. You can control how many files Word displays by using the RecentFiles object associated with the Application object and setting the RecentFiles object's Maximum property to a number between 0 and 9.

DisplayScreenTips

Boolean

Controls whether Word displays pop-up tooltips for text having comments, for footnotes and end notes, and for hyperlinked text.

DisplayScrollBars

Boolean

Controls whether Word displays the horizontal and vertical scroll bars for all open documents.

DisplayStatusBar

Boolean

Controls whether Word displays the status bar for the active document. The value of this property can change when the active document changes.

Height

Integer

Sets the height in points of the main Word window when WindowState is set to wdWindowStateNormal.

Left

Integer

Sets the left position in points of the main Word window when WindowState is set to wdWindowStateNormal.

ShowWindowsInTaskbar

Boolean

Sets whether Word creates a window and taskbar button for each open document (TRue), which is also called SDI mode, or uses one window that contains all open document windows (False), which is also called MDI mode.

Top

Integer

Sets the top position in points of the main Word window when WindowState is set to wdWindowStateNormal.

Visible

Boolean

Sets whether the Word application window is visible.

Width

Integer

Sets the width in points of the main Word window when WindowState is set to WdWindowState.wdWindowStateNormal.

WindowState

WdWindowState

Sets whether the main Word window is minimized (wdWindowStateMinimize), maximized (wdWindowStateMaximize), or normal (wdWindowStateNormal). The Width, Height, Left, and Top settings have an effect only when WindowState is set to wdWindowStateNormal.


Listing 8.4. A VSTO Customization and Helper Function That Modifies the Word User Interface

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim app As Word.Application = Me.Application     app.DisplayAutoCompleteTips = GetBool("Autocomplete tips?")     app.DisplayRecentFiles = GetBool("Display recent files?")     app.DisplayScreenTips = GetBool("Display screen tips?")     app.DisplayScrollBars = GetBool("Display scroll bars?")     app.DisplayStatusBar = _       GetBool("Display status bar for active document?")      app.ShowWindowsInTaskbar = GetBool("Multiple windows?")      app.Visible = GetBool("Visible application window?")      app.WindowState = Word.WdWindowState.wdWindowStateNormal      app.Width = 200      app.Height = 300      app.Top = 50      app.Left = 100    End Sub    Private Function GetBool(ByVal message As String) As Boolean      Return MsgBox(message, MsgBoxStyle.YesNo, _        "Word UI Demo") = MsgBoxResult.Yes    End Function 


Properties That Return Active or Selected Objects

The 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.

Table 8.2. Application Properties That Return Active Objects

Property Name

Type

What It Does

ActiveDocument

Document

Returns the active Documentthe document that has focus within Word. If there are no open documents, an exception is thrown.

ActivePrinter

String

Returns a String for the active printer (for example, "EpsonStylus COLOR 860 ESC/P 2 on LPT1:").

ActiveWindow

Window

Returns the active Window. If no windows are open, an exception is thrown.

NormalTemplate

Template

Returns a Template object representing the Normal template (normal.dot).

Selection

Selection

Returns a Selection object that represents the current selection or insertion point in the document.


Listing 8.5. A VSTO Customization and Helper Function That Examines Active Objects

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim app As Word.Application = Me.Application     ShowItem("ActiveDocument", app.ActiveDocument.Name)     ShowItem("ActivePrinter", app.ActivePrinter)     ShowItem("ActiveWindow", app.ActiveWindow.Caption)     ShowItem("NormalTemplate", app.NormalTemplate.Name)     ShowItem("Selection", app.Selection.Start.ToString())   End Sub   Private Sub ShowItem(ByVal name As String, _     ByVal status As String)     MsgBox(status, MsgBoxStyle.OkOnly, name)   End Sub End Class 


Properties That Return Important Collections

The 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.

Table 8.3. Application Properties That Return Important Collections

Property Name

Type

What It Does

CommandBars

CommandBars

Returns the CommandBars collection, which lets you modify or add to Word's toolbars and menus. Changes made to toolbars and menus are saved in a template or in a document; use the CustomizationContext property to set where changes are stored.

Dialogs

Dialogs

Returns the Dialogs collection, which lets you access the built-in Word dialog boxes (of which there are more than 240). You can show a particular dialog box using this collection.

Documents

Documents

Returns the Documents collection, which contains all the documents open in Word.

FontNames

FontNames

Returns the FontNames collection, which contains all the fonts that are installed and available for use.

KeyBindings

KeyBindings

Returns the KeyBindings collection, which lets you examine, modify, and add key shortcuts that are assigned to Word commands.

RecentFiles

RecentFiles

Returns the RecentFiles collection, which lets you examine and reopen any of the nine most recently opened files.

TaskPanes

TaskPanes

Returns the TaskPanes collection, which allows you to show or detect which of the 14 built-in task panes are visible.

Templates

Templates

Returns the Templates collection, which lets you examine the installed templates and their properties.

Windows

Windows

Returns the Windows collection, which represents the windows open in Word.


Listing 8.6. A VSTO Customization and Helper Function That Examines Collections

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim app As Word.Application = Me.Application     Show(String.Format("There are {0} command bars.", _       app.CommandBars.Count))     Show(String.Format("CommandBar 1 is {0}.", app.CommandBars(1).Name))     Show(String.Format("There are {0} dialog boxes.", _       app.Dialogs.Count))     Show("Click OK to invoke the About dialog...")     app.Dialogs(Word.WdWordDialog.wdDialogHelpAbout).Show()     Show(String.Format("There are {0} open documents.", _       app.Documents.Count))     Dim doc As Word.Document = app.Documents.Item(1)     Show(String.Format("Document 1 is {0}.", doc.Name))     Show(String.Format("There are {0} fonts.", _       app.FontNames.Count))     Show(String.Format("FontName 1 is {0}.", app.FontNames(1)))     Show(String.Format("There are {0} key bindings.", _       app.KeyBindings.Count))     If app.KeyBindings.Count > 0 Then       Show(String.Format("KeyBinding 1 is {0}.", _         app.KeyBindings(1).Command))     End If     Show(String.Format("There are {0} recent files.", _       app.RecentFiles.Count))     Show(String.Format("RecentFile 1 is {0}.", _       app.RecentFiles(1).Name))     Show(String.Format("There are {0} task panes.", _       app.TaskPanes.Count))     Show("Click OK to activate the help task pane.")     app.TaskPanes( _       Word.WdTaskPanes.wdTaskPaneHelp).Visible = True     Show(String.Format("There are {0} templates.", _       app.Templates.Count))     Show(String.Format("Template 1 is {0}.", _       app.Templates.Item(1).FullName))     Show(String.Format("There are {0} windows.", _       app.Windows.Count))     Show(String.Format("Window 1 is {0}.", _       app.Windows.Item(1).Caption))   End Sub   Private Sub Show(ByVal text As String)     MsgBox(text, MsgBoxStyle.OkOnly, "Active Objects")   End Sub End Class 


Navigating a Document

The 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:

  • wdBrowseComment

  • wdBrowseEdit

  • wdBrowseEndnote

  • wdBrowseField

  • wdBrowseFind

  • wdBrowseFootnote

  • wdBrowseGoTo

  • wdBrowseGraphic

  • wdBrowseHeading

  • wdBrowsePage

  • wdBrowseSection

  • wdBrowseTable

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

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _      ByVal e As System.EventArgs) Handles Me.Startup     ' Generate some random text in the document.     Dim r As Word.Range = Range()     Dim builder As New System.Text.StringBuilder()     Dim rand As New Random()     Dim i As Integer     For i = 0 To 1000       builder.Append(rand.NextDouble().ToString())       builder.Append(vbCrLf)     Next     r.Text = builder.ToString()     ' Browse by page     Application.Browser.Target = Word.WdBrowseTarget.wdBrowsePage     Dim j As Integer     For j = 0 To 10       Application.Browser.Next()       Application.Selection.Text = String.Format( _         "<<<<<< PAGE {0} >>>>>>" & vbCrLf, j)     Next   End Sub End Class 


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 Options

The 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

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim o As Word.Options = Application.Options     o.CreateBackup = DisplayAndSet( _       "Always create backup copy", o.CreateBackup)     o.AllowFastSave = DisplayAndSet( _       "Allow fast saves", o.AllowFastSave)     o.BackgroundSave = DisplayAndSet( _       "Allow background saves", o.BackgroundSave)     o.SavePropertiesPrompt = DisplayAndSet( _       "Prompt for document properties", o.SavePropertiesPrompt)     o.SaveNormalPrompt = DisplayAndSet( _       "Prompt to save Normal template", o.SaveNormalPrompt)     Application.Dialogs( _       Word.WdWordDialog.wdDialogToolsOptionsSave).Show()   End Sub   Private Function DisplayAndSet(ByVal settingName As String, _     ByVal settingValue As Boolean) As Boolean     Dim title As String = "Options Demo"     Dim checkState As String = "unchecked."     Dim action As String = "check"     If settingValue Then       checkState = "checked."       action = "uncheck"     End If     Dim message As String = String.Format( _       "{0} is {1}." & vbCrLf & _       "Do you want to {2} it?", settingName, checkState, action)     Dim r As MsgBoxResult = MsgBox(message, _       MsgBoxStyle.YesNo, title)     If r = MsgBoxResult.Yes Then       Return Not settingValue     Else       Return settingValue     End If   End Function End Class 


Working with the New and Getting Started Document Task Panes

The 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

Public Class ThisDocument   Private app As Word.Application   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     app = Me.Application     Dim Newfile As Office.NewFile = app.NewDocument     Newfile.Add("c:\foo.doc", _       Office.MsoFileNewSection.msoNew, _       "msoNew msoEdit", _       Office.MsoFileNewAction.msoEditFile)     Newfile.Add("c:\foo.doc", _       Office.MsoFileNewSection.msoNewfromTemplate, _       "msoNewFromTemplate msoCreateNewFile", _       Office.MsoFileNewAction.msoCreateNewFile)     Newfile.Add("c:\foo.doc", _       Office.MsoFileNewSection.msoNewfromExistingFile, _       "msoNewFromExistingFile msoCreateNewFile", _       Office.MsoFileNewAction.msoCreateNewFile)     Newfile.Add("http://www.microsoft.com", _       Office.MsoFileNewSection.msoBottomSection, _       "msoBottomSection msoOpenFile", _       Office.MsoFileNewAction.msoOpenFile)     Newfile.Add("c:\foo.doc", _       Office.MsoFileNewSection.msoOpenDocument, _       "msoOpenDocument msoEdit", _       Office.MsoFileNewAction.msoEditFile)     ' Execute the "New" command found     ' in the File menu to show     ' the new document task pane.     Application.CommandBars.FindControl(1, 18).Execute()   End Sub   Private Sub ThisDocument_BeforeClose(ByVal sender As Object, _     ByVal e As System.ComponentModel.CancelEventArgs) _     Handles Me.BeforeClose     Dim NewFile As Office.NewFile = app.NewDocument     NewFile.Remove("c:\foo.doc", _       Office.MsoFileNewSection.msoNew, _       "msoNew msoEdit", _       Office.MsoFileNewAction.msoEditFile)     NewFile.Remove("c:\foo.doc", _       Office.MsoFileNewSection.msoNewfromTemplate, _       "msoNewFromTemplate msoCreateNewFile", _       Office.MsoFileNewAction.msoCreateNewFile)     NewFile.Remove("c:\foo.doc", _       Office.MsoFileNewSection.msoNewfromExistingFile, _       "msoNewFromExistingFile msoCreateNewFile", _       Office.MsoFileNewAction.msoCreateNewFile)     NewFile.Remove("http://www.microsoft.com", _       Office.MsoFileNewSection.msoBottomSection, _       "msoBottomSection msoOpenFile", _       Office.MsoFileNewAction.msoOpenFile)     NewFile.Remove("c:\foo.doc", _       Office.MsoFileNewSection.msoOpenDocument, _       "msoOpenDocument msoEdit", _       Office.MsoFileNewAction.msoEditFile)   End Sub End Class 


Working with the File Save Format Options

The 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 Boxes

Word 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

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim f As Office.FileDialog = Application.FileDialog( _       Office.MsoFileDialogType.msoFileDialogFilePicker)     f.AllowMultiSelect = True     f.ButtonName = "Copy to C:\"     f.InitialFileName = System.Environment.GetFolderPath( _       Environment.SpecialFolder.Desktop)     f.InitialView = _       Office.MsoFileDialogView.msoFileDialogViewList     f.Title = "Select files to copy to c:\"     Dim result As Integer = f.Show()     If result = -1 Then       For Each s As String In f.SelectedItems         Dim fileName As New System.IO.FileInfo(s)         System.IO.File.Copy(fileName.FullName, _           "c:\" + fileName.Name)       Next     End If   End Sub End Class 


User Information

Word'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 Spelling

Word 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

Public Class ThisDocument   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     Dim badString As String = "This are grammatically incorrect."     Dim goodString As String = "This is grammatically correct."     Dim badString2 As String = "I cain't spel."     Dim goodString2 As String = "I can spell."     Dim singleWord As String = "spel"     MsgBox(String.Format("{0}" & vbCrLf & _       "CheckGrammar returns {1}.", _       badString, Application.CheckGrammar(badString)))     MsgBox(String.Format("{0}" & vbCrLf & _       "CheckGrammar returns {1}.", _       goodString, Application.CheckGrammar(goodString)))     MsgBox(SpellingHelper(badString2))     MsgBox(SpellingHelper(goodString2))     MsgBox(String.Format( _       "Getting spelling suggestions for {0}.", _       singleWord))     Dim suggestions As Word.SpellingSuggestions = _       Application.GetSpellingSuggestions(singleWord)     For Each s As Word.SpellingSuggestion In suggestions       MsgBox(s.Name)     Next   End Sub   Private Function SpellingHelper(ByVal phrase As String) _     As String     Dim correctSpelling As Boolean     correctSpelling = Application.CheckSpelling(phrase)     If correctSpelling Then       Return String.Format("{0} is spelled correctly.", phrase)     Else       Return String.Format( _         "{0} is spelled incorrectly.", phrase)     End If   End Function End Class 


Exiting Word

The 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

Public Class ThisDocument   Private app As Word.Application   Private Sub ThisDocument_Startup(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles Me.Startup     app = Me.Application     Range.Text = "Sample text"     app.Quit(False)   End Sub End Class 





Visual Studio Tools for Office(c) Using Visual Basic 2005 with Excel, Word, Outlook, and InfoPath
Visual Studio Tools for Office: Using Visual Basic 2005 with Excel, Word, Outlook, and InfoPath
ISBN: 0321411757
EAN: 2147483647
Year: N/A
Pages: 221

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net