- Referencing a COM Component in Visual Studio .NET
- Referencing a COM Component Using Only the .NET Framework SDK
- Example: A Spoken Hello, World Using the Microsoft Speech API
- The Type Library Importer
- Using COM Objects in ASP.NET Pages
- An Introduction to Interop Marshaling
- Common Interactions with COM Objects
- Using ActiveX Controls in .NET Applications
- Deploying a .NET Application That Uses COM
- Example: Using Microsoft Word to Check Spelling
- Conclusion
Example: Using Microsoft Word to Check Spelling
To end the chapter, let's apply everything we've learned to a larger example. This example application is a very simple word processor, shown in Figure 3.15, which uses Microsoft Word for its spellchecker functionality. The user can type inside the application, and then click the Check Spelling button. Each misspelled word (according to Microsoft Word) is highlighted in red and underlined. At any time, the user can right-click a word and choose from a list of correctly spelled replacements supplied by Microsoft Word. The application also gives an option to ignore words with all uppercase letters. When selected, such a word isn't ever marked as misspelled, and alternate spellings aren't suggested when right-clicking it.
Figure 3.15 The example word processor.
The code, shown in C# in Listing 3.5, demonstrates the use of by-reference optional parameters, error handling with COM objects, and enumerating over a collection. The C# version is shown because calling the methods with optional parameters requires extra work. The Visual Basic .NET version on this book's Web site looks much less messy when calling these methods.
To compile or run this example, you must have Microsoft Word on your computer. The sample uses Word 2002, which ships with Microsoft Office XP. If you have a different version of Word installed, it should still work (as long as you use the appropriate type library instead of the one mentioned in step 2).
If you have Visual Studio .NET, here are the steps for creating and running this application:
Create a new Visual C# Windows Application project.
Add a reference to Microsoft Word 10.0 Object Library using the method explained at the beginning of this chapter.
View the code for Form1.cs in your project, and change its contents to the code in Listing 3.5. One way to view the code is to right-click on the filename in the Solution Explorer window and select View Code.
Build and run the project.
Otherwise, if all you have is the .NET Framework SDK, you can perform the following steps:
-
Create and save a Form1.cs file with the code in Listing 3.5. The Windows Forms code inside InitializeComponent is omitted, but the complete source code is available on this book's Web site.
Use TLBIMP.EXE to generate an Interop Assembly for the Microsoft Word type library as follows:
TlbImp "C:\Program Files\Microsoft Office\Office10\msword.olb"
The path for the input file may need to change depending on your computer's settings. If a PIA for the Word type library is available, you should download it from MSDN Online and use that instead of running TLBIMP.EXE.
Compile the code, referencing all the needed assemblies:
csc /t:winexe Form1.cs /r:Word.dll /r:System.Windows.Forms.dll
_/r:System.Drawing.dll /r:System.dll
Run the generated executable.
Listing 3.5 Form1.cs. Using Microsoft Word Spell Checking in C#
1: using System; 2: using System.Drawing; 3: using System.Windows.Forms; 4: 5: public class Form1 : Form 6: { 7: // Visual controls 8: private RichTextBox richTextBox1; 9: private Button button1; 10: private CheckBox checkBox1; 11: private ContextMenu contextMenu1; 12: 13: // Required designer variable 14: private System.ComponentModel.Container components = null; 15: 16: // The Word application object 17: private Word.Application msWord; 18: 19: // Two fonts used to display normal words and misspelled words 20: private Font normalFont = new Font("Times New Roman", 12); 21: private Font errorFont = new Font("Times New Roman", 12, 22: FontStyle.Underline); 23: 24: // Objects that need to be passed by-reference when calling Word 25: private object missing = Type.Missing; 26: private object ignoreUpper; 27: 28: // Event handler used for the ContextMenu when 29: // the user clicks on spelling suggestions 30: private EventHandler menuHandler; 31: 32: // Constructor 33: public Form1() 34: { 35: // Required for Windows Form Designer support 36: InitializeComponent(); 37: menuHandler = new System.EventHandler(this.Menu_Click); 38: } 39: 40: // Called when the form is loading. Initializes Microsoft Word. 41: protected override void OnLoad(EventArgs e) 42: { 43: base.OnLoad(e); 44: 45: try 46: { 47: msWord = new Word.Application(); 48: 49: // Call this in order for GetSpellingSuggestions to work later 50: msWord.Documents.Add(ref missing, ref missing, ref missing, 51: ref missing); 52: } 53: catch (System.Runtime.InteropServices.COMException ex) 54: { 55: if ((uint)ex.ErrorCode == 0x80040154) 56: { 57: MessageBox.Show("This application requires Microsoft Word " + 58: "to be installed for spelling functionality. " + 59: "Since Word can't be located, the spelling functionality " + 60: "is disabled.", "Warning"); 61: button1.Enabled = false; 62: checkBox1.Enabled = false; 63: } 64: else 65: { 66: MessageBox.Show("Unexpected initialization error. " + 67: ex.Message + "\n\nDetails:\n" + ex.ToString(), 68: "Unexpected Initialization Error", MessageBoxButtons.OK, 69: MessageBoxIcon.Error); 70: this.Close(); 71: } 72: } 73: catch (Exception ex) 74: { 75: MessageBox.Show("Unexpected initialization error. " + ex.Message + 76: "\n\nDetails:\n" + ex.ToString(), 77: "Unexpected Initialization Error", MessageBoxButtons.OK, 78: MessageBoxIcon.Error); 79: this.Close(); 80: } 81: } 82: 83: // Clean up any resources being used 84: protected override void Dispose(bool disposing) 85: { 86: if (disposing) 87: { 88: if (components != null) 89: { 90: components.Dispose(); 91: } 92: } 93: base.Dispose(disposing); 94: } 95: 96: // Required method for Designer support 97: private void InitializeComponent() 98: { 99: ... 100: } 101: 102: // The main entry point for the application 103: [STAThread] 104: public static void Main() 105: { 106: Application.Run(new Form1()); 107: } 108: 109: // Checks the spelling of the word contained in the string argument. 110: // Returns true if spelled correctly, false otherwise. 111: // This method ignores words in all uppercase letters if checkBox1 112: // is checked. 113: private bool CheckSpelling(string word) 114: { 115: ignoreUpper = checkBox1.Checked; 116: 117: // Pass a reference to Type.Missing for each 118: // by-reference optional parameter 119: 120: return msWord.CheckSpelling(word, // Word 121: ref missing, // CustomDictionary 122: ref ignoreUpper, // IgnoreUppercase 123: ref missing, // AlwaysSuggest 124: ref missing, // CustomDictionary2 125: ref missing, // CustomDictionary3 126: ref missing, // CustomDictionary4 127: ref missing, // CustomDictionary5 128: ref missing, // CustomDictionary6 129: ref missing, // CustomDictionary7 130: ref missing, // CustomDictionary8 131: ref missing, // CustomDictionary9 132: ref missing); // CustomDictionary10 133: } 134: 135: // Checks the spelling of the word contained in the string argument. 136: // Returns a SpellingSuggestions collection, which is empty if the word 137: // is spelled correctly. 138: // This method ignores words in all uppercase letters if checkBox1 139: // is checked. 140: private Word.SpellingSuggestions GetSpellingSuggestions(string word) 141: { 142: ignoreUpper = checkBox1.Checked; 143: 144: // Pass a reference to Type.Missing for each 145: // by-reference optional parameter 146: 147: return msWord.GetSpellingSuggestions(word, // Word 148: ref missing, // CustomDictionary 149: ref ignoreUpper, // IgnoreUppercase 150: ref missing, // MainDictionary 151: ref missing, // SuggestionMode 152: ref missing, // CustomDictionary2 153: ref missing, // CustomDictionary3 154: ref missing, // CustomDictionary4 155: ref missing, // CustomDictionary5 156: ref missing, // CustomDictionary6 157: ref missing, // CustomDictionary7 158: ref missing, // CustomDictionary8 159: ref missing, // CustomDictionary9 160: ref missing); // CustomDictionary10 161: } 162: 163: // Called when the "Check Spelling" button is clicked. 164: // Checks the spelling of each word and changes the font of 165: // each misspelled word. 166: private void button1_Click(object sender, EventArgs e) 167: { 168: try 169: { 170: // Return all text to normal since 171: // underlined spaces might be left behind 172: richTextBox1.SelectionStart = 0; 173: richTextBox1.SelectionLength = richTextBox1.Text.Length; 174: richTextBox1.SelectionFont = normalFont; 175: 176: // Beginning location in the RichTextBox of the next word to check 177: int index = 0; 178: 179: // Enumerate over the collection of words obtained from String.Split 180: foreach (string s in richTextBox1.Text.Split(null)) 181: { 182: // Select the word 183: richTextBox1.SelectionStart = index; 184: richTextBox1.SelectionLength = s.Length; 185: 186: // Trim off any ending punctuation in the selected text 187: while (richTextBox1.SelectionLength > 0 && 188: Char.IsPunctuation( 189: richTextBox1.Text[index + richTextBox1.SelectionLength - 1])) 190: { 191: richTextBox1.SelectionLength--; 192: } 193: 194: // Check the word's spelling 195: if (!CheckSpelling(s)) 196: { 197: // Mark as incorrect 198: richTextBox1.SelectionFont = errorFont; 199: richTextBox1.SelectionColor = Color.Red; 200: } 201: else 202: { 203: // Mark as correct 204: richTextBox1.SelectionFont = normalFont; 205: richTextBox1.SelectionColor = Color.Black; 206: } 207: 208: // Update to point to the character after the current word 209: index = index + s.Length + 1; 210: } 211: } 212: catch (Exception ex) 213: { 214: MessageBox.Show("Unable to check spelling. " + ex.Message + 215: "\n\nDetails:\n" + ex.ToString(), "Unable to Check Spelling", 216: MessageBoxButtons.OK, MessageBoxIcon.Error); 217: } 218: } 219: 220: // Called when the user clicks anywhere on the text. If the user 221: // clicked the right mouse button, this determines the word underneath 222: // the mouse pointer (if any) and presents a context menu of 223: // spelling suggestions. 224: private void richTextBox1_MouseDown(object sender, MouseEventArgs e) 225: { 226: try 227: { 228: if (e.Button == MouseButtons.Right) 229: { 230: // Get the location of the mouse pointer 231: Point point = new Point(e.X, e.Y); 232: 233: // Find the index of the character underneath the mouse pointer 234: int index = richTextBox1.GetCharIndexFromPosition(point); 235: 236: // Length of the word underneath the mouse pointer 237: int length = 1; 238: 239: // If the character under the mouse pointer isn't whitespace, 240: // determine what the word is and display spelling suggestions 241: 242: if (!Char.IsWhiteSpace(richTextBox1.Text[index])) 243: { 244: // Going backward from the index, 245: // figure out where the word begins 246: while (index > 0 && !Char.IsWhiteSpace( 247: richTextBox1.Text[index-1])) { index--; length++; } 248: 249: // Going forward, figure out where the word ends, 250: // making sure to not include punctuation except for apostrophes 251: // (This works for English.) 252: while (index + length < richTextBox1.Text.Length && 253: !Char.IsWhiteSpace(richTextBox1.Text[index + length]) && 254: (!Char.IsPunctuation(richTextBox1.Text[index + length]) || 255: richTextBox1.Text[index + length] == Char.Parse("'")) 256: ) length++; 257: 258: // Now that we've found the entire word, select it 259: richTextBox1.SelectionStart = index; 260: richTextBox1.SelectionLength = length; 261: 262: // Clear the context menu in case 263: // there are items on it from last time 264: contextMenu1.MenuItems.Clear(); 265: 266: // Enumerate over the SpellingSuggestions collection 267: // returned by GetSpellingSuggestions 268: foreach (Word.SpellingSuggestion s in 269: GetSpellingSuggestions(richTextBox1.SelectedText)) 270: { 271: // Add the menu item with the suggestion text and the 272: // Menu_Click handler 273: contextMenu1.MenuItems.Add(s.Name, menuHandler); 274: } 275: 276: // Display special text if there are no spelling suggestions 277: if (contextMenu1.MenuItems.Count == 0) 278: { 279: contextMenu1.MenuItems.Add("No suggestions."); 280: } 281: else 282: { 283: // Add two more items whenever there are spelling suggestions. 284: // Since there is no event handler, nothing will happen when 285: // these are clicked. 286: contextMenu1.MenuItems.Add("-"); 287: contextMenu1.MenuItems.Add("Don't change the spelling."); 288: } 289: 290: // Now that the menu is ready, show it 291: contextMenu1.Show(richTextBox1, point); 292: } 293: } 294: } 295: catch (Exception ex) 296: { 297: MessageBox.Show("Unable to give spelling suggestions. " + 298: ex.Message + "\n\nDetails:\n" + ex.ToString(), 299: "Unable to Give Spelling Suggestions", MessageBoxButtons.OK, 300: MessageBoxIcon.Error); 301: } 302: } 303: 304: // Called when a spelling suggestion is clicked on the context menu. 305: // Replaces the currently selected text with the text 306: // from the item clicked. 307: private void Menu_Click(object sender, EventArgs e) 308: { 309: // The suggestion should be spelled correctly, 310: // so restore the font to normal 311: richTextBox1.SelectionFont = normalFont; 312: richTextBox1.SelectionColor = Color.Black; 313: 314: // Obtain the text from the MenuItem and replace the SelectedText 315: richTextBox1.SelectedText = ((MenuItem)sender).Text; 316: } 317: }
Line 17 declares the Application object used to communicate with Microsoft Word, and Lines 2021 define the two different fonts that the application usesone for correctly spelled words and one for misspelled words. Line 25 defines a Missing instance that is used for accepting the default behavior of optional parameters. It's defined as a System.Object due to C#'s requirement of exact type matching when passing by-reference parameters. The ignoreUpper variable in Line 26 tracks the user's preference about checking uppercase words, and the menuHandler delegate in Line 30 handles clicks on the context menu presented when a user right-clicks. Events and delegates are discussed in Chapter 5.
The OnLoad method in Lines 4181 handles the initialization of Microsoft Word. If Word isn't installed, it displays a warning message and simply disables spell checking functionality rather than ending the entire program. The CheckSpelling method in Lines 113133 returns true if the input word is spelled correctly, or false if it is misspelled (according to Word's own CheckSpelling method). The GetSpellingSuggestions method in Lines 140161 returns a SpellingSuggestions collection returned by Word for the input string. These CheckSpelling and GetSpellingSuggestions methods wrap their corresponding Word methods simply because the original methods are cumbersome with all of the optional parameters that must be dealt with explicitly.
The button1_Click method in Lines 166218, which is called when the user clicks the Check Spelling button, enumerates over every word inside the RichTextBox control and calls CheckSpelling to determine whether to underline each word. The richTextBox1_MouseDown method in Lines 224302 determines if the user has right-clicked on a word. If so, it dynamically builds a context menu with the collection of spelling suggestions returned by the call to GetSpellingSuggestions in Line 269. The Menu_Click method in Lines 307316 is the event handler associated with any misspelled words displayed on the context menu. When the user clicks a word in the menu, this method is called and Line 315 replaces the original text with the corrected text.
Microsoft Word is an out-of-process COM server, meaning that it runs in a separate process from the application that's using it. You can see this process while the example application runs by opening Windows Task Manager and looking for WINWORD.EXE.
Using Windows Task Manager, here's something you can try to see exception handling in action:
Start the example application.
Open Windows Task Manager by Pressing Ctrl+Alt+Delete (and, if appropriate, clicking the Task Manager button) and end the WINWORD.EXE process, as shown in Figure 3.16. The exact step depends on your version of Windows, but there should be a button marked either End Process or End Task.
Although the server has been terminated, the client application is still running. Now press the Check Spelling button on the example application.
Observe the dialog box that appears, which is shown in Figure 3.17. This is the result of the catch statement in the button1_Click method.
Figure 3.16 Ending the WINWORD.EXE process while the client application is still running.
Figure 3.17 Handliing a comexception caused by a failure.