Spelling Checking Using Microsoft Word Object Library in WPF

This article shows how to check for misspelled words in a document (in a WPF Rich TextBox) using the COM Object "Microsoft Word Object Library".

To exploit the Spellchecker feature in our app, we are using the Microsoft Word Object Library. This is a COM object and you can add the COM DLL into your project by right-clicking the project's References then selecting "Add Reference"  then go to the "COM" Tab and select "Microsoft Word 14.0 Object Library" then click "OK".

WPFSpellerChecker.jpg

Now we add a Rich TextBox in the WPF Grid (to show the contents), a List Box (to show suggested words for a misspelled word) and a button (to check spelling). So in this way we add a DLL reference and finish our GUI design for this app.

On running this app, we paste the contents on the Rich TextBox using a default Cut-Copy-Paste context menu (see below).

WPFSpellerChecker1.jpg

WPFSpellerChecker2.jpg

Logic

In order to check the spelling and get spelling suggestions for a misspelled word, we create the following objects:

Microsoft.Office.Interop.Word.Application appWord;
Microsoft.Office.Interop.Word.SpellingSuggestions CorrectionsCollection;


To check the spellings, we first parse the text written in the TextBox and retireve all the wrods.

Then for each word, we call the "CheckSpelling" method of the Word.Application object.

IsWordCorrect = appWord.CheckSpelling(word, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt);

In the preceding method, only the first argument, "word", is a required argument but all the other arguments are optional. For more details, refer to the MSDN documentation at:

http://msdn.microsoft.com/en-us/library/office/ff822597.aspx

If we get the "IsWrodCorrect" boolean flag as false (in other words a misspelled word) then we highlight the word with a different color in the RichTextBox as follows:

//Highlighing the misspelled word in RichTextBox using TextRange class

TextRange tr = new TextRange(richTextBox1.Document.ContentEnd, richTextBox1.Document.ContentEnd);

tr.Text = word + " ";

tr.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);

To get the spelling suggestions for a misspelled word, we double-click the highlighted word and all the word suggestions are listed in a ListBox underneath the TextBox (see the screenshot below). The following is the code to get suggested words in the RichTextBox_DoubleClick event handler:
 

//Getting the selected word from RichTextBox

TextRange tr = new TextRange(richTextBox1.Selection.Start, richTextBox1.Selection.End);

 

//Calling GetSpellingSuggestion() Mathod by ing a selected word

CorrectionsCollection = appWord.GetSpellingSuggestions(tr.Text);

 

//Adding all suggested words into a ListBox

if (CorrectionsCollection.Count > 0)

{

    int iWord = 0;

    for (iWord = 1; iWord <= CorrectionsCollection.Count; iWord++)

    {

        listBoxSuggestedWords.Items.Add(CorrectionsCollection[iWord].Name);

    }

}


Full Code

Here is the full code with comments:
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

 

namespace WpfSpellChecker

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    public partial class MainWindow : Window

    {

 

        Microsoft.Office.Interop.Word.Application appWord;

        Microsoft.Office.Interop.Word.SpellingSuggestions CorrectionsCollection;

        Object nullArgmnt = null;

 

        public MainWindow()

        {

            InitializeComponent();

        }

 

        private void Window_Loaded(object sender, RoutedEventArgs e)

        {

            appWord = new Microsoft.Office.Interop.Word.Application();

 

            //adding new document to word application

            appWord.Documents.Add();

 

        }

 

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)

        {

            if (appWord != null)

            {

                appWord.Quit(ref nullArgmnt, ref nullArgmnt, ref nullArgmnt);

            }

        }

 

        private void btn_FilterWords_Click(object sender, RoutedEventArgs e)

        {

            listBoxSuggestedWords.Items.Clear();

            SpellCheck();

        }

 

        private void SpellCheck()

        {

            Boolean IsWordCorrect;

 

            try

            {

                //Getting Text from RichTextBox from start to end using TextRange class

                string myText = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;

 

                //Parsing text by a space character to identify different words

                string[] wordBag = myText.Split(' ');

 

                //Removing old text in order to put new text after spell checking

                richTextBox1.Document.Blocks.Clear();

 

                //Iterating each word

                foreach (string word in wordBag)

                {

                    //Checking Spelling for each word

                    IsWordCorrect = appWord.CheckSpelling(word, ref nullArgmnt, ref nullArgmnt, ref nullArgmnt,

                                                                ref nullArgmnt, ref nullArgmnt, ref nullArgmnt,

                                                                ref nullArgmnt, ref nullArgmnt, ref nullArgmnt,

                                                                ref nullArgmnt, ref nullArgmnt, ref nullArgmnt);

 

                    if (IsWordCorrect == false)

                    {

                        //Highlighing the misspelled word in RichTextBox using TextRange class

                        TextRange tr = new TextRange(richTextBox1.Document.ContentEnd, richTextBox1.Document.ContentEnd);

                        tr.Text = word + " ";

                        tr.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);

                    }

                    else

                    {

                        //setting no Highlighing for the correct words in RichTextBox using TextRange class

                        TextRange tr = new TextRange(richTextBox1.Document.ContentEnd, richTextBox1.Document.ContentEnd);

                        tr.Text = word + " ";

                        tr.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.White);

                    }

                }

            }

            catch (Exception Ex)

            {

                MessageBox.Show("Exception occurred:" + Ex.Message);

            }

        }

 

        private void richTextBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)

        {

            listBoxSuggestedWords.Items.Clear();

 

            //Getting the selected word from RichTextBox

            TextRange tr = new TextRange(richTextBox1.Selection.Start, richTextBox1.Selection.End);

 

            //Calling GetSpellingSuggestion() Mathod by ing a selected word

            CorrectionsCollection = appWord.GetSpellingSuggestions(tr.Text);

 

            //Adding all suggested words into a ListBox

            if (CorrectionsCollection.Count > 0)

            {

                int iWord = 0;

                for (iWord = 1; iWord <= CorrectionsCollection.Count; iWord++)

                {

                    listBoxSuggestedWords.Items.Add(CorrectionsCollection[iWord].Name);

                }

            }

        }

    }

}