Search code examples
c#.netwinformsoffice-2007spell-checking

Implement Word Spell check in Windows Form App


I have an In-house windows form app that I would like to use Spell Checking in. Everyone has Office 2007 installed so I shouldn't have an issue there but I am having trouble getting this to fully work.

Here is what I have:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;

namespace Refraction.Spelling
{
    public static class SpellCheckers
    {
        public static string CheckSpelling(string text)
        {
            Word.Application app = new Word.Application();
 object nullobj = Missing.Value;
                object template = Missing.Value;
                object newTemplate = Missing.Value;
                object documentType = Missing.Value;
                object visible = true;
                object optional = Missing.Value;
            object savechanges = false;
            Word._Document doc = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);

        doc.Words.First.InsertBefore(text);
        Word.ProofreadingErrors errors = doc.SpellingErrors;

        var ecount = errors.Count;
        doc.CheckSpelling(ref optional, ref optional, ref optional, ref optional, 
            ref optional, ref optional, ref optional, ref optional, ref optional, 
            ref optional, ref optional, ref optional);
        object first = 0;
        object last = doc.Characters.Count - 1;
        var results = doc.Range(ref first, ref last).Text;
        doc.Close(ref savechanges, ref nullobj, ref nullobj);
        app.Quit(ref savechanges, ref nullobj, ref nullobj);

        return results;
    }
}

}

I use this like so:

memDirectionsToAddress.Text = SpellCheckers.CheckSpelling(memDirectionsToAddress.Text);

Now this successfully pops up the SpellCheck Dialog from Word and detects any misspelled wordsbut I cannot get it to make the corrections in the WinForm app.

Also, it leaves this "Shell" of a Word Doc open with the corrected text. How do I not show that or at least make it go away?

Two things:

  • First, though the "shell" closes it Flashes everytime. Any solutions to that?
  • Second, the Spell Check Dialog does not appear on TOP, what can I set to correct that?

Thanks


Solution

  • The next steps would be:

    1. Pull the corrected text back out of the document.
    2. Close the document. (If there's only one document open in Word, you may want to close or hide the Word application.)
    3. Return the corrected text to the calling function.

    More info: