Special Edition Using Visual Basic.NET

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET

By Brian Siler, Jeff Spotts

Table of Contents
Chapter 25.  Interacting with Other Applications

Just like Excel, Microsoft Word exposes a set of COM objects that can be utilized by other programs to drive a session of Word. Again, this object library, which will be accessed via a .NET wrapper around the COM component, will allow a program to control Word just like a user sitting at a keyboard.

Adding a Reference to the Word Object Library

As with Excel, in order for an application to be able to interact with Microsoft Word, you must first add a reference to the Word object library to your application. Again, you will do so by creating a .NET wrapper around the Word COM component. Follow these steps to begin enhancing the sample application for Word interactivity:

  1. Begin with the ControlOfficeDemo sample application that you created in the previous section.

  2. In the Solution Explorer window, right-click References under the ControlOfficeDemo project; then select Add Reference from the Context menu.

  3. In the Add Reference dialog box, click the COM tab to indicate that you want to add a COM reference.

  4. This time, select Microsoft Word 9.0 Object Library under Component Name, and then click the Select button to place this library in the Selected Components box.

  5. Again, if you are presented with a primary interop assembly message asking if you would like to have a wrapper generated, click Yes. This will cause a .NET wrapper for the Word COM component to be generated, allowing the COM-based Word component to be used in the .NET environment.

  6. Notice that the Solution Explorer window now shows a reference for Word in addition to the Excel and Office references that were added earlier.

Now that a reference to the Word object library has been added to the application, you can add code to remote control Word in much the same manner as you controlled Excel in the first part of the example.

Adding Word Functionality

We will now enhance the sample application to allow it to control Word. Just as we added the Imports Excel statement to the Form1 class to bring in the Excel namespace, we will include the Word namespace with an Imports Word statement.

Next, we will declare a Word.Application variable named WordApp that will act as our representation of an instance of Word. Follow these steps to set up the namespace reference, create an object variable representing the Word application, invoke an instance of Word, and cause the Word instance to be visible to the user:

  1. Add a Button control named btnWord to Form1's interface. Set the button's Text property to LaunchWord.

  2. At the top of the code window for the Form1 class, add the statement Imports Word just below the Imports Excel statement that you added earlier. This will make the Word namespace available to Form1.

  3. Add the following code to the Click event handler for btnWord:

    Dim WordApp As Word.Application WordApp = New Word.Application() WordApp.Visible = True

Note

The variables for this part of the example are being declared at procedure level because they will not be used in any other procedures.

Save and run the application at this point, and then click the Launch Word button. An instance of Microsoft Word will start; however, there will not be a document open inside the Word window. Stop the sample program; then manually close the Word window.

Creating a Word Document

Just as you had to write code to open a blank workbook inside the copy of Excel that your program invoked, you must write code to have Word create a new blank document. Add the following code to the Click event handler for btnWord to accomplish this:

Dim MyDoc As Word.Document MyDoc = WordApp.Documents.Add

Now, when you save and run the application, a new blank Word document is created and opened inside the copy of the Word application that was started. Be sure to manually close the instance of Word when you close the program.

Adding Text to the Word Document

The Word document is represented by the variable MyDoc, which was created as a result of invoking the Add method of the Documents collection of WordApp, which is our variable that represents the running instance of Word. To add text to the document, which of course is the goal of using Word, we will work with the Range property of the Word document. The Range property exposes a Range object, which represents a range of characters in the document. The Range property is expressed by specifying the beginning and ending character positions that define the desired range; for example, MyDoc.Range(0,5) would represent the first five characters of the document (the counting is zero-based). The ending value, 5, is not included in the range. If you leave out the starting and ending character values, the Range property refers to the entire document.

Use Listing 25.3 to complete the Click event handler for btnWord. This will create a simple Executive Summary report using the sales figures entered by the user into the text boxes.

Listing 25.3 Remote Controlling Microsoft Word

MyDoc.Range(0, 0).InsertAfter("Executive Profit Summary") MyDoc.Range(0, 24).Font.Name = "Arial" MyDoc.Range(0, 24).Font.Size = 18 MyDoc.Range(0, 24).Font.Color = Word.WdColor.wdColorBlue MyDoc.Range.InsertParagraphAfter() MyDoc.Range(0, 24).ParagraphFormat.Alignment = _ Word.WdParagraphAlignment.wdAlignParagraphCenter MyDoc.Range.InsertParagraphAfter() Dim sTemp As String sTemp = "In the current reporting period, we had total expenses of " sTemp += FormatCurrency(txtExpenses.Text) sTemp += " against sales of " & FormatCurrency(txtSales.Text) sTemp += ", for a Net Profit of " sTemp += FormatCurrency(txtSales.Text - txtExpenses.Text) & "." MyDoc.Range.InsertAfter(sTemp)

Listing 25.3 uses the InsertAfter method of the Range object, which causes text to be inserted after the specified range. The Range object's Font property is used to format the font appropriately. The InsertParagraphAfter method, which is equivalent to pressing Enter in the Word document, is used to start a new paragraph. The Alignment subproperty of the ParagraphFormat property sets the paragraph alignment of the range to be centered (using the wdAlignParagraphCenter member of the Word.WdParagraphAlignment enumeration). Finally, a temporary String variable is used to construct the actual text of the report, using information from the two text boxes, and then to add the information to the Word document.

Save and run the application again. You will see a completed Word document, which has been constructed from the figures that the user typed into the text boxes, as illustrated in Figure 25.6. Again, close the Word document manually.

Figure 25.6. This Word document was created by a VB program.

Printing and Closing the Document

The last bit of code we will add to the sample application will print the customized report and then close the Word application. Of course, depending on your plans for the program, you may want to leave it open for the user to edit, add more text, and so on.

Add the following two lines of code to the end of the btnWordClick event handler:

MyDoc.PrintOut() WordApp.Quit(False)

The first line uses the PrintOut method of the Word document object to print a single copy of the report on the user's default printer. (A number of parameters are available to customize the PrintOut method with options such as number of copies, which page(s) to print, and so on.) The second line uses the Quit method of the Word application object to shut down the instance of Word, specifying False as the value of the Save parameter, which tells Word not to try to save the (unsaved) open document.

This last time, when you run the application, the report will be printed after it is constructed; then the Word application will automatically shut down.

Tip

If you want your application to create and print a Word document without the user seeing Word appear, simply remove the line that sets the Visible property of the Word application object to True.

Listing 25.4 contains the complete btnWordClick event handler.

Listing 25.4 ControlOfficeDemo.ZIP Code to Add Word Functionality

Private Sub btnWord_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnWord.Click Dim WordApp As Word.Application WordApp = New Word.Application() WordApp.Visible = True Dim MyDoc As Word.Document MyDoc = WordApp.Documents.Add MyDoc.Range(0, 0).InsertAfter("Executive Profit Summary") MyDoc.Range(0, 24).Font.Name = "Arial" MyDoc.Range(0, 24).Font.Size = 18 MyDoc.Range(0, 24).Font.Color = Word.WdColor.wdColorBlue MyDoc.Range.InsertParagraphAfter() MyDoc.Range(0, 24).ParagraphFormat.Alignment = _ Word.WdParagraphAlignment.wdAlignParagraphCenter MyDoc.Range.InsertParagraphAfter() Dim sTemp As String sTemp = "In the current reporting period, we had total expenses of " sTemp += FormatCurrency(txtExpenses.Text) sTemp += " against sales of " & FormatCurrency(txtSales.Text) sTemp += ", for a Net Profit of " sTemp += FormatCurrency(txtSales.Text - txtExpenses.Text) & "." MyDoc.Range.InsertAfter(sTemp) MyDoc.PrintOut() WordApp.Quit(False) End Sub


    Team-Fly    
    Top
     

    Категории