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

Article translations Article translations
Article ID: 302817 - View products that this article applies to.
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.
Expand all | Collapse all

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.
  1. 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.
  2. Add a reference to the Word object library. To do this, follow these steps:
    1. On the Project menu, click Add Reference.
    2. 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
    3. Click OK in the Add References dialog box to accept your selections.
  3. On the View menu, click ToolBox. Add a a button to Form1.
  4. Double-click Button1 to generate a definition for the button's Click event handler.
  5. 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 = "Handle Events for Microsoft Word Using C#.";
    	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(
    		"DocumentBeforeClose ( You are closing " + doc.Name + " )");
    }
    
    private void oWord_DocumentBeforeSave(Word.Document doc, ref bool SaveAsUI, ref bool Cancel)
    {
    	Debug.WriteLine(
    		"DocumentBeforeSave ( You are saving " + doc.Name + " )");
    }
    
    private void oWord_DocumentChange()
    {
    	Debug.WriteLine("DocumentChange");
    }
    
    private void oWord_WindowBeforeDoubleClick(Word.Selection sel, ref bool Cancel)
    {
    	Debug.WriteLine(
    		"WindowBeforeDoubleClick (Selection is: " + sel.Text + " )");
    }
    
    private void oWord_WindowBeforeRightClick(Word.Selection sel, ref bool Cancel)
    {
    	Debug.WriteLine(
    		"WindowBeforeRightClick (Selection is: " + sel.Text + " )");
    
    }
  6. 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;
    					
  7. Press F5 to build and then run the program.
  8. 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:
    1. Double-click anywhere in the document; the WindowBeforeDoubleClick event fires.
    2. Right-click anywhere in the document; the WindowBeforeRightClick event fires.
    3. Save the document; the DocumentBeforeSave event fires.
    4. Close the document; the DocumentBeforeClose and DocumentChange events fire.
    5. 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.

REFERENCES

For additional information about automating Word, click the article numbers below to view the articles in the Microsoft Knowledge Base:
301659 How To Automate Microsoft Word to Perform Mail Merge from Visual C# .NET
285333 INFO: Word 2002 MailMerge Event Code Demonstration
For more information, see the following Microsoft Developer Network (MSDN) Web site:
Microsoft Office Development with Visual Studio
http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx

Properties

Article ID: 302817 - Last Review: June 29, 2007 - Revision: 5.2
APPLIES TO
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Word 2002
Keywords: 
kbautomation kbhowto KB302817

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com