Home > Articles > Programming > Windows Programming

This chapter is from the book

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:

  1. Create a new Visual C# Windows Application project.

  2. Add a reference to Microsoft Word 10.0 Object Library using the method explained at the beginning of this chapter.

  3. 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.

  4. Build and run the project.

Otherwise, if all you have is the .NET Framework SDK, you can perform the following steps:

  1. 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.

  2. 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.

  3. 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

  4. 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 20–21 define the two different fonts that the application uses—one 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 41–81 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 113–133 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 140–161 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 166–218, 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 224–302 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 307–316 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:

  1. Start the example application.

  2. 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.

  3. Although the server has been terminated, the client application is still running. Now press the Check Spelling button on the example application.

  4. 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020