Microsoft KB Archive/302817

= How To Handle Events for Word by Using Visual C# .NET =

Article ID: 302817

Article Last Modified on 6/29/2007

-

APPLIES TO


 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Word 2002 Standard Edition

-



This article was previously published under Q302817



For a Microsoft Visual Basic .NET version of this article, see 302816.

For a Microsoft Visual C++ version of this article, see 309294.



SUMMARY
This article illustrates how to handle events in Word from an Automation client that is created with Visual C# .NET.



MORE INFORMATION
With C#, Word events are based on delegates. Word defines the events that it will raise, providing callback functions. The delegate is a template for single method that meets Word's requirement for the callback function for one event. The C# program creates a specific object that is based on that delegate. That object complies with the Word callback function's need for a specific reference.

Events Supported by Both Word 2000 and Word 2002
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
 * Event                  | Description                                         |
 * Close                  | Occurs when a document is closed.                   |
 * DocumentBeforeClose    | Occurs immediately before any open document closes. |
 * DocumentBeforePrint    | Occurs before any open document is printed.         |
 * DocumentBeforeSave     | Occurs before any open document is saved.           |
 * DocumentChange         | Occurs when a new document is created, when an      |
 * | existing document is opened, or when another       |
 * | document is made the active document.              |
 * DocumentOpen           | Occurs when a document is opened.                   |
 * GotFocus               | Occurs when the focus is moved to an embedded       |
 * | ActiveX control.                                   |
 * LostFocus              | Occurs when the focus is moved from an embedded     |
 * | ActiveX control.                                   |
 * New                    | Occurs when a new document that is based on the     |
 * | template is created. A procedure for the New event |
 * | runs only if it is stored in a template.           |
 * NewDocument            | Occurs when a new document is created.              |
 * Open                   | Occurs when a document is opened.                   |
 * Quit                   | Occurs when the user quits Word.                    |
 * WindowActivate         | Occurs when any document window is activated.       |
 * WindowBeforeDoubleClick | Occurs when the editing area of a document window  |
 * | is double-clicked, before the default double-click |
 * | action.                                            |
 * WindowBeforeRightClick | Occurs when the editing area of a document window   |
 * | is right-clicked, before the default right-click   |
 * | action.                                            |
 * WindowDeactivate       | Occurs when any document window is deactivated.     |
 * WindowSelectionChange  | Occurs when the selection changes in the active     |
 * | document window.                                   |

Events Supported by Word 2002 Only
+-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
 * EPostageInsert             | Occurs when a user inserts electronic postage |
 * | into a document.                             |
 * EPostagePropertyDialog     | Occurs when a user clicks the E-postage       |
 * | Properties button (located in the Labels and |
 * | Envelopes dialog box) or the Print Electronic |
 * | Postage toolbar button. This event allows a  |
 * | third-party software application to intercept |
 * | and show their properties dialog box.        |
 * MailMergeAfterMerge        | Occurs after all records in a mail merge have |
 * | merged successfully.                         |
 * MailMergeAfterRecordMerge  | Occurs after each record in the data source   |
 * | successfully merges in a mail merge.         |
 * MailMergeBeforeMerge       | Occurs when a merge is executed before any    |
 * | records merge.                               |
 * MailMergeBeforeRecordMerge | Occurs as a merge is executed for the         |
 * | individual records in a merge.               |
 * MailMergeDataSourceLoad    | Occurs when the data source is loaded for a   |
 * | mail merge.                                  |
 * MailMergeDataSourceValidate | Occurs when a user performs address          |
 * | verification by clicking Validate in the     |
 * | Mail Merge Recipients dialog box.            |
 * MailMergeWizardSendToCustom | Occurs when the Custom button is clicked on  |
 * | step 6 of the Mail Merge Wizard.             |
 * MailMergeWizardStateChange | Occurs when a user changes from a specified   |
 * | step to a specified step in the Mail Merge   |
 * | Wizard.                                      |
 * WindowSize                 | Occurs when the application window is resized |
 * | or moved.                                    |

Create a C# .NET Automation Client that Handles Word Events
The following steps demonstrate how a C# .NET Automation client can handle events that are raised by Word. The code sample demonstrates how to handle some, but not all, Word events; you can modify the code by using the technique that is illustrated in the code to handle additional events.  Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Under Project types click Visual C# Projects, then click Windows Application under Templates. Form1 is created by default. Add a reference to the Word object library. To do this, follow these steps:  On the Project menu, click Add Reference. On the COM tab, locate Microsoft Word 10.0 Object Library, and then click Select.NOTE: If you have not already done so, it is recommended that you download and install the Microsoft Office XP Primary Interop Assemblies (PIAs). For additional information about Office XP PIAs, click the article number below to view the article in the Microsoft Knowledge Base:

328912 INFO: Microsoft Office XP PIAs Are Available for Download

 Click OK in the Add References dialog box to accept your selections.</li></ol> </li> On the View menu, click ToolBox. Add a a button to Form1.</li> Double-click Button1 to generate a definition for the button's Click event handler.</li>  In the code window, replace the following code private void button1_Click(object sender, System.EventArgs e) {

} with: private Word.ApplicationClass oWord; private void button1_Click(object sender, System.EventArgs e) { //===== Create a new document in Word ============== // Create an instance of Word and make it visible. oWord = new Word.ApplicationClass; oWord.Visible = true;

// Local declarations. Word._Document oDoc; Object oMissing = System.Reflection.Missing.Value;

// Add a new document. oDoc = oWord.Documents.Add(ref oMissing,ref oMissing,       ref oMissing,ref oMissing); // Clean document

// Add text to the new document. oDoc.Content.Text = &quot;Handle Events for Microsoft Word Using C#.&quot;; oDoc = null;

//============ Set up the event handlers ===============

oWord.DocumentBeforeClose += new Word.ApplicationEvents3_DocumentBeforeCloseEventHandler(        oWord_DocumentBeforeClose ); oWord.DocumentBeforeSave += new Word.ApplicationEvents3_DocumentBeforeSaveEventHandler(        oWord_DocumentBeforeSave ); oWord.DocumentChange += new Word.ApplicationEvents3_DocumentChangeEventHandler(        oWord_DocumentChange ); oWord.WindowBeforeDoubleClick += new Word.ApplicationEvents3_WindowBeforeDoubleClickEventHandler(        oWord_WindowBeforeDoubleClick ); oWord.WindowBeforeRightClick += new Word.ApplicationEvents3_WindowBeforeRightClickEventHandler(        oWord_WindowBeforeRightClick ); }

// The event handlers.

private void oWord_DocumentBeforeClose(Word.Document doc, ref bool Cancel) {   Debug.WriteLine(        &quot;DocumentBeforeClose ( You are closing &quot; + doc.Name + &quot; )&quot;); }

private void oWord_DocumentBeforeSave(Word.Document doc, ref bool SaveAsUI, ref bool Cancel) {   Debug.WriteLine(        &quot;DocumentBeforeSave ( You are saving &quot; + doc.Name + &quot; )&quot;); }

private void oWord_DocumentChange {   Debug.WriteLine(&quot;DocumentChange&quot;); }

private void oWord_WindowBeforeDoubleClick(Word.Selection sel, ref bool Cancel) {   Debug.WriteLine(        &quot;WindowBeforeDoubleClick (Selection is: &quot; + sel.Text + &quot; )&quot;); }

private void oWord_WindowBeforeRightClick(Word.Selection sel, ref bool Cancel) {   Debug.WriteLine(        &quot;WindowBeforeRightClick (Selection is: &quot; + sel.Text + &quot; )&quot;);

} </li>  Scroll to the top of the code window, and then add the following lines of code to the end of the list of using directives: using System.Diagnostics; using Word = Microsoft.Office.Interop.Word; </li> Press F5 to build and then run the program.</li> Click button1 on the form to start Word, create a new Word document, and then set up the event handlers. Test the event handlers, as follows: <ol style="list-style-type: lower-alpha;"> Double-click anywhere in the document; the WindowBeforeDoubleClick event fires.</li> Right-click anywhere in the document; the WindowBeforeRightClick event fires.</li> Save the document; the DocumentBeforeSave event fires.</li> Close the document; the DocumentBeforeClose and DocumentChange events fire.</li> In Visual Studio, on the View menu, click Other Windows and then click Output to view the Output window. The Output window displays a trace of the events that were handled as well as the order in which the events were handled.</li></ol> </li></ol>

<div class="references_section">