Microsoft KB Archive/824022

= How to handle events in Word by using Visual C# .NET =

Article ID: 824022

Article Last Modified on 5/17/2007

-

APPLIES TO


 * Microsoft Office Word 2007
 * Microsoft Office Word 2003
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-



SUMMARY
This article describes how to handle events in Microsoft Word 2000, in Microsoft Word 2002, in Microsoft Office Word 2003, and in Microsoft Office Word 2007 from an Automation client that is created by using Microsoft Visual C# .NET.



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

Recognize events that are supported by Word 2000, by Word 2002, by Word 2003, and by Word 2007
+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+
 * 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.                                   |

Recognize events that are supported by Word 2002, by Word 2003, and by Word 2007
+-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
 * EPostageInsert             | Occurs when a user inserts electronic postage |
 * | in 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 permits 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.                                    |

Recognize events that are supported by Word 2003 and by Word 2007
+-+ +-+ +-+ +-+ +-+ +-+ +-+
 * DocumentSync               | Occurs when the local copy of a document      |
 * | that is part of a document workspace is      |
 * | synchronized with the copy on the server.    |
 * EPostageInsertEx           | Occurs when a user inserts electronic postage |
 * | in a document.                               |
 * XMLAfterInsert             | Occurs when a user adds a new XML element to a|
 * | document. If more than one element is added  |
 * | to the document at the same time (for example,|
 * | when cutting and pasting XML), the event fires|
 * | for each element that is inserted.           |
 * XMLBeforeDelete            | Occurs when a user deletes an XML element     |
 * | from a document. If more than one element    |
 * | is deleted from the document at the same time,|
 * | the event fires for each element that is     |
 * | deleted.                                     |
 * XMLSelectionChange         | Occurs when the parent XML node of the        |
 * | current selection changes.                   |
 * XMLValidationError         | Occurs when there is a validation error in    |
 * | the document.                                |

Create a Visual C# .NET Automation client that handles Word events
The following steps describe how a Visual C# .NET Automation client handles the events that Word raises. 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 sample to handle additional events.  Start Microsoft Visual Studio .NET or Microsoft Visual Studio .NET 2003. On the File menu, click New, and then click Project. Under Project Types, click Visual C# Projects. Under Templates, click Windows Application.

By default, Form1 is created. 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 11.0 Object Library, and then click Select.</li> In the Add References dialog box, click OK to accept your selections.</li></ol> </li> On the View menu, click ToolBox.

Add a button to Form1.</li> Double-click Button1 to generate a definition for the Click event handler for the button.</li>  In the Code window, locate the following code: private void button1_Click(object sender, System.EventArgs e) {

} Replace the previous code with the following code: private Word.Application 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.Application; 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.ApplicationEvents4_DocumentBeforeCloseEventHandler(        oWord_DocumentBeforeClose ); oWord.DocumentBeforeSave += new Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(        oWord_DocumentBeforeSave ); oWord.DocumentChange += new Word.ApplicationEvents4_DocumentChangeEventHandler(        oWord_DocumentChange ); oWord.WindowBeforeDoubleClick += new Word.ApplicationEvents4_WindowBeforeDoubleClickEventHandler(        oWord_WindowBeforeDoubleClick ); oWord.WindowBeforeRightClick += new Word.ApplicationEvents4_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 the using directives: using System.Diagnostics; using Word = Microsoft.Office.Interop.Word; </li></ol>

Test the code
<ol> Press F5 to build the program, and then to run the program.</li> On the form, click Button1 to start Word, to create a new Word document, and to set up the event handlers.</li> To test the event handlers, follow these steps: <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 event fires. The DocumentChange event fires.</li> On the View menu, click Other Windows in Visual Studio. NET. Click Output to view the Output window.

The Output window displays a trace of the events that were handled and also the order that the events were handled in.</li></ol> </li></ol>

<div class="references_section">