Article Options
Recently Viewed
Premium Sponsor
Premium Sponsor

 »  Home  »  Windows Development  »  Interop  »  Adding Spelling and Grammar Checking Functions into VB.NET Applications
Adding Spelling and Grammar Checking Functions into VB.NET Applications
by David Wasserman | Published  05/24/2003 | Interop | Rating:
David Wasserman

David Wasserman is a Senior Software Developer residing in Toronto, Canada. He has over 10 years industry experience in a vast array of technologies and programming languages. David has also consulted for many companies in the banking, retail and communications industries via Grand Solutions Consulting Inc, where he is Vice-President. In recent years, David's focus has been working with Microsoft technologies, including Visual Basic, VB.NET, C#, ASP, ASP .NET, SQL Server and MS Access development. David can be reached at david@grandconsult.com.

 

View all articles by David Wasserman...
Adding Spelling and Grammar Checking Functions into VB.NET Applications

Article source code: spellcheck.zip

Introduction

Many applications can be enhanced by including spelling and grammar checking capabilities. Users will greatly appreciate these features and in addition, applications will appear more professional as they mimic popular programs like MS Word. This article will demonstrate how to add these functions to a Visual Basic.NET Windows Form project. It's quite easy to do, and only requires that the client application have Microsoft Word installed. The code in this article has been successfully tested with Microsoft Word 97, 2000, XP and 2003 Beta 2.

Create a new Windows Application project in Visual Studio.NET. The Form will contain two buttons and one TextBox control. Add controls to the Form with the following settings:

TypeNameText
ButtonbtnSpellCheckSpell Check
ButtonbtnGrammarCheckGrammar Check
TextboxTextbox1 

The Object Libraries for Microsoft Word are not written natively in .NET. A COM wrapper is required to import the required spelling and grammar components. Right click on References under the Windows Application in the Solution Explorer. Click on Add Reference... and then click on the COM tab in the Add Reference dialog box. Scroll down the list until you find Microsoft Word Object Library. There will be a version number associated with it, in my case (Word 2002), I see version 10.0. Select this object by clicking on the Select button and then on the OK button.

Code

It is now time to get down to coding. The first thing to do is add the following Imports statement:

Imports System.Runtime.InteropServices

This will provide for the necessary error handling further on in the code.

The next thing to do is create a subroutine for calling the spell checking component. This subroutine is called from the click events of the btnSpellCheck and btnGrammarCheck. One Boolean parameter is passed to determine if the spell checker or grammar checker is invoked. Keep in mind that the grammar checker also checks spelling, whereas the spelling checker only checks spelling and not grammar:

    Private Sub SpellOrGrammarCheck(ByVal blnSpellOnly As Boolean)

The next thing we'll do is define some object variables to hold the instance of a Word application, Word document and an IDataObject to hold data returned from the clipboard. All of this occurs with a Try...Catch block:

        Try
            Dim objWord As Object
            Dim objTempDoc As Object
            Dim iData As IDataObject

The data to spell check is contained in TextBox1. If there is nothing contained in the text, then it is fair to skip the rest of this subroutine and just exit:

            If TextBox1.Text = "" Then
                Exit Sub
            End If

The next thing to do is instantiate the Word application, add a temporary document to it and position Word so it's not visible:

            objWord = New Word.Application()
            objTempDoc = objWord.Documents.Add
            objWord.Visible = False

            objWord.WindowState = 0
            objWord.Top = -3000

Copy the text contents of TextBox1 to the clipboard:

            Clipboard.SetDataObject(TextBox1.Text)

Now that we have the data in the clipboard we can copy it to our temporary document and activate the spell/grammar check on the Word document:

            With objTempDoc
                .Content.Paste()
                .Activate()
                If blnSpellOnly Then
                    .CheckSpelling()
                Else
                    .CheckGrammar()
                End If

After the spell/grammar checker has run and any changes have been made by the user, transfer the contents back to TextBox1:

                .Content.Copy()
                iData = Clipboard.GetDataObject
                If iData.GetDataPresent(DataFormats.TextThen
                    TextBox1.Text = CType(iData.GetData(DataFormats.Text), _
                        String)
                End If
                .Saved = True
                .Close()
            End With

It's now time to quit Word and send back a message to the user; in the same way that Word does when the spell/grammar checker is complete:

            objWord.Quit()

            MessageBox.Show("The spelling check is complete."_
                "Spell Checker"MessageBoxButtons.OK_
                MessageBoxIcon.Information)

The last thing to do in this routine is to add in the error handling Catch statements. Two Catch blocks are defined; one to determine if Word is installed, as it is required; and the other to handle gracefully any other errors by displaying an error message:

        Catch COMExcep As COMException
            MessageBox.Show_
                "Microsoft Word must be installed for Spell/Grammar Check " _
                & "to run.""Spell Checker")

        Catch Excep As Exception
            MessageBox.Show("An error has occurred.""Spell Checker")

        End Try

    End Sub

Finally, the code to call the above routine must be added to the grammar and spell checker buttons:

    Private Sub btnSpellCheck_Click(ByVal sender As System.Object_
        ByVal e As System.EventArgsHandles btnSpellCheck.Click
        SpellOrGrammarCheck(True)
    End Sub

    Private Sub btnGrammarCheck_Click(ByVal sender As System.Object_
        ByVal e As System.EventArgsHandles btnGrammarCheck.Click
        SpellOrGrammarCheck(False)
    End Sub

Conclusion

This article has described how to use the spelling and grammar checking facilities of Microsoft Word in a stand-alone Windows application. Using object oriented features and COM Interop, the addition of these features to your own applications can add that professional touch while utilizing software that is widely available and already installed in many cases.

One thing you may want to consider when adding this functionality to your own applications would be to disable the buttons or menu items for spelling/grammar options if Word isn't detected on the client computer. This would give the polished appearance of a professional application.

The attached to the article solution is based on Word 2002 and references Office/Word v10 Object Library. It may not be the version you’ve got (for instance - Office 2000, Version 9) – please expect this and remove Office/Word v10 Object Library references from the project and replace them with the appropriate one for your version.

The following is a complete listing of all code presented in this article:

Imports System.Runtime.InteropServices

Public Class Form1
    Inherits System.Windows.Forms.Form

    ' Invokes either the spell or grammar checker.  
    Private Sub SpellOrGrammarCheck(ByVal blnSpellOnly As Boolean)

        Try
            ' Create Word and temporary document objects.
            Dim objWord As Object
            Dim objTempDoc As Object
            ' Declare an IDataObject to hold the data returned from the 
            ' clipboard.
            Dim iData As IDataObject

            ' If there is no data to spell check, then exit sub here.
            If TextBox1.Text = "" Then
                Exit Sub
            End If

            objWord = New Word.Application()
            objTempDoc = objWord.Documents.Add
            objWord.Visible = False

            ' Position Word off the screen...this keeps Word invisible 
            ' throughout.
            objWord.WindowState = 0
            objWord.Top = -3000

            ' Copy the contents of the textbox to the clipboard
            Clipboard.SetDataObject(TextBox1.Text)

            ' With the temporary document, perform either a spell check or a 
            ' complete
            ' grammar check, based on user selection.
            With objTempDoc
                .Content.Paste()
                .Activate()
                If blnSpellOnly Then
                    .CheckSpelling()
                Else
                    .CheckGrammar()
                End If
                ' After user has made changes, use the clipboard to
                ' transfer the contents back to the text box
                .Content.Copy()
                iData = Clipboard.GetDataObject
                If iData.GetDataPresent(DataFormats.TextThen
                    TextBox1.Text = CType(iData.GetData(DataFormats.Text), _
                        String)
                End If
                .Saved = True
                .Close()
            End With

            objWord.Quit()

            MessageBox.Show("The spelling check is complete."_
                "Spell Checker"MessageBoxButtons.OK_
                MessageBoxIcon.Information)

            ' Microsoft Word must be installed. 
        Catch COMExcep As COMException
            MessageBox.Show_
                "Microsoft Word must be installed for Spell/Grammar Check " _
                & "to run.""Spell Checker")

        Catch Excep As Exception
            MessageBox.Show("An error has occured.""Spell Checker")

        End Try

    End Sub

    Private Sub btnSpellCheck_Click(ByVal sender As System.Object_
        ByVal e As System.EventArgsHandles btnSpellCheck.Click
        SpellOrGrammarCheck(True)
    End Sub

    Private Sub btnGrammarCheck_Click(ByVal sender As System.Object_
        ByVal e As System.EventArgsHandles btnGrammarCheck.Click
        SpellOrGrammarCheck(False)
    End Sub

End Class
Generated using PrettyCode.Encoder
How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:4.07272727272725 out of 5
 55 people have rated this page
Article Score33452
Comments    Submit Comment

Comment #1  (Posted by Kent on 06/18/2003)

Anybody know how to do this without .net? What are they calling what I use now? ASP 3.0 or ASP Classic????

Help is appreciated.
 
Comment #2  (Posted by Ian Anderson on 10/03/2003)

One weakness of the code is that it has to be changed for every installed version of Word. Is there a way for the application to sense the version of Word installed at runtime and use the appropriate library?

 
Comment #3  (Posted by peh1696 on 11/25/2003)

i found out there is a bug in the coding.....
in this part...
If blnSpellOnly Then
.checkspelling()
Else
.CheckGrammar()
End If

should be change into this....
If blnSpellOnly = True Then
.checkspelling()
Else
.CheckGrammar()
End If
Everything will works fine.....TQ
 
Comment #4  (Posted by A.Satish Kumar on 12/04/2003)

This Is Great But Only thing is the spelling & grammar checks are not affected only when the spelling & grammar is closed not the usual way as in MS-WORD can anybody look into this...........?????????
 
Comment #5  (Posted by Tom on 01/28/2004)

Getting error: Type 'Word.Application' is not defined.
 
Comment #6  (Posted by Dawn on 01/30/2004)

How do you check if Word is installed first (as suggested by the article?)

Also, when I click "OK" to end the spell check, Word flashes onto the screen which is very annoying and surprising for the user. Can this be supressed?
 
Comment #7  (Posted by XTab on 01/31/2004)

Try this code:
Imports Microsoft.Win32

Function IsWordInstalled() As Boolean
' Define the RegistryKey objects for the registry hives.
' Note that you need Imports Microsoft.Win32 for this to work
Dim regClasses As RegistryKey = Registry.ClassesRoot

' Check whether Microsoft Word is installed on this computer,
' by searching the HKEY_CLASSES_ROOT\Word.Application key.
Dim regWord As RegistryKey = regClasses.OpenSubKey("Word.Application")
If regWord Is Nothing Then
IsWordInstalled = False
Else
IsWordInstalled = True
End If
' Always close Registry keys after using them.
regWord.Close()
End Function

Cheers
XTab
 
Comment #8  (Posted by lferdinand on 02/05/2004)

Can this be done using ASP .NET??? I need a spellchecker for the web.
 
Comment #9  (Posted by Andy Yeo on 03/18/2004)

I have a few questions to ask of you if you dont mind.

My first questions is this, can I do the above with Visual C Net ?

I know this is possible but I have no idea how I should go about it.

Perhaps can you please kindly provide some Visual C Net code for me to do the following :-

1) prompt the user to key in a sentence in English, e.g. :- "how are you today?"

2) assign the Sentence into a Variable

2) call up the ms word grammar checker to check and immediately correct the english sentence

3) output the corrected sentence to the screen

4) ms word should not call up the grammar checking screen of word, it should go ahead and correct all the grammartical errors in the sentence without any user intervention

I would like to kindly ask you if you can do the above for me please ?

Thank you so much for your time.

Hope to hear from you soon.

Andy

Andy_Kheemeng@yahoo.com.sg
 
Comment #10  (Posted by Stephen H on 03/30/2004)

Hey I found a very simple solution to the problem with the Word window popping up at the end of the spellcheck. Something (maybe the ".saved = true") set the Word application to be visible, so simply set it to false right before the ".close()"

...
.Saved = True
objWord.visible = False ' This line of code fixes the error
.Close()
End With

Also another thing that I was able to do is check two textboxes consecutively... I sent the textboxes as parameters then... well just take a look...

****************************************************************************************************************
Private Sub SpellCheck(ByVal blnSpellOnly As Boolean, ByVal TextBox1 As TextBox, ByVal TextBox2 As TextBox)
Try
Dim concated As String
Dim firstStr As Integer
Dim objWord As Object
Dim objTempDoc As Object
Dim iData As IDataObject

If TextBox1.Text = "" And TextBox2.Text = "" Then
Exit Sub
End If
objWord = New Word.Application()
objTempDoc = objWord.Documents.Add
objWord.Visible = False

objWord.WindowState = 0
objWord.Top = -3000

Clipboard.SetDataObject(TextBox1.Text)

With objTempDoc
.Content.Paste()
.Activate()
If blnSpellOnly Then
.CheckSpelling()
Else
.CheckGrammar()
End If
.Content.Copy()
iData = Clipboard.GetDataObject
If iData.GetDataPresent(DataFormats.Text) Then
TextBox1.Text = CType(iData.GetData(DataFormats.Text), _
String)
End If

' The following is for the second text box
Clipboard.SetDataObject(TextBox2.Text)
.Content.Paste()
.Activate()
objWord.visible = False ' This is needed again here
If blnSpellOnly Then
.CheckSpelling()
Else
.CheckGrammar()
End If
.Content.Copy()
iData = Clipboard.GetDataObject
If iData.GetDataPresent(DataFormats.Text) Then
TextBox2.Text = CType(iData.GetData(DataFormats.Text), _
String)
End If

.Saved = True
objWord.visible = False
.Close()
End With

objWord.Quit()

MessageBox.Show("The spelling check is complete.", "Spell Checker", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch COMExcep As COMException
MessageBox.Show("Microsoft Word must be installed for Spell/Grammar Check " & "to run.", "Spell Checker")

Catch Excep As Exception
MessageBox.Show("An error has occurred.", "Spell Checker")


End Try
End Sub

**********************************************************************************************************

I think that you can also do the grammar and spelling checks consecutively as well with this technique, in fact... I think I just might try that

I hope this helps some people out

And if your curious how the grammar part turns out and need a sample code just email me (I dont think I'm gonna be back on to look for replys)

-Stephen
 
Comment #11  (Posted by Carlos Perez on 06/09/2004)

How I can Spell in English and in Spanish.

Do i can change the Language to spell?

Tahnks i would apreciate your answers
 
Comment #12  (Posted by Sam on 08/23/2004)

Excellent article, but....

I found that I had to instance the word.application object slightly differently, probably because I'm using version 11 (office 2003)

objWord = New Microsoft.Office.Interop.Word.Application



 
Comment #13  (Posted by Isabelle on 11/23/2004)

I try to use the code. I am getting errors and it opens multiple instances of word when I have multiple textboxes with mispelled words in the form.
 
Comment #14  (Posted by pac on 01/07/2005)
Rating
this article is very interesting
as a starter
i have 2 question to ask
1) im planing to use the same mechanism but the spell check or grammar check will be trigger each the user end a word. i was wondering it was possible
2)
my second when the application will be call for word, will it be on the server or on the use machine, because the application im runing will be install on the server but we can install word on the server.

hope to hear from u thanks
 
Comment #15  (Posted by an unknown user on 02/01/2005)
Rating
Pretty neat, close to what I want, but I need something to spell check on the fly.
 
Comment #16  (Posted by an unknown user on 02/03/2005)
Rating
****
 
Comment #17  (Posted by Bassam Basamad on 04/23/2005)
Rating
Hi..Just One Question..Could you tell me how i can use this code in asp.net.? that i can use the textarea control to checking spelling and grammar in the client by clicking button submit to return me the result (suggesttions)..from the server..if there is word installed..?
 
Comment #18  (Posted by Dhyan on 06/04/2005)
Rating
Can anyone tell me how to add reference to a project during runtime,due to the problem of different version installation of MsWord. The application doesn't work with different versions of word.
 
Comment #19  (Posted by pav on 06/23/2005)
Rating
could u help me the same spell checking for multiple controls in c#. Actually in the code the spell checking suggestions window (doesnt load correctly. sometimes will be in background) & the background form controls simply gets distorted sometimes during ths process. iam developing a windows app. where spell check has to be carried out to many controls. sometimes even 20-30. how do u think this method can be scaled. Please let me know soon
 
Comment #20  (Posted by an unknown user on 07/05/2005)
Rating
that's good but why its very slow
 
Comment #21  (Posted by an unknown user on 07/25/2005)
Rating
o o god yes o o god yes
 
Comment #22  (Posted by an unknown user on 11/22/2005)
Rating
This is a pretty cool windows application; would like one for a web application.
 
Comment #23  (Posted by an unknown user on 11/22/2005)
Rating
This is a pretty cool windows application; would like one for a web application.
 
Comment #24  (Posted by arnolem on 12/06/2005)
Rating
I have make a function who check with all textbox, but on pc with office2003, after the check, i can see the word document during 1/2seconde. I have try to add ObjWord.Visible =False but i have the problem.

*********

When i remove the final msgBox to use my fonction with many textbox, i have a problèm with ClipBoard, that is the solution :

End With
Clipboard.SetDataObject("")
Me.Update()
objWord.Quit()
 
Comment #25  (Posted by Mario on 12/13/2005)
Rating
very good
 
Comment #26  (Posted by Danry Imbert on 02/09/2006)
Rating
I have a question... what about if i use this with a RichTextBox, how do i keep the RTF formatting during the Spell/Grammar check, cause it always take away all the formatting it has.
 
Comment #27  (Posted by Dilip bhalala on 06/17/2006)
Rating
Hi
how to set language in this code.
I have one combo box that contain some language name i want to set one of them for the spell checking. if i select english UK then it will check in that dictionary.

i hopeful for replay



 
Comment #28  (Posted by an unknown user on 08/27/2006)
Rating
because just like it
 
Comment #29  (Posted by chanmi on 08/27/2006)
Rating
just bad
 
Comment #30  (Posted by an unknown user on 02/15/2007)
Rating
It worked for me
 
Comment #31  (Posted by an unknown user on 03/13/2007)
Rating
Really cool
 
Comment #32  (Posted by Paolo on 03/13/2007)
Rating
Really cool !!!
 
Comment #33  (Posted by an unknown user on 05/02/2007)
Rating
Great tip with excellent documentation.
 
Comment #34  (Posted by an unknown user on 05/16/2007)
Rating
I have same query as Denry,
I have a question... what about if i use this with a RichTextBox, how do i keep the RTF formatting during the Spell/Grammar check, cause it always take away all the formatting it has.
 
Comment #35  (Posted by an unknown user on 06/02/2007)
Rating
Useful knowlwdge imparted. Thanx
 
Comment #36  (Posted by an unknown user on 12/22/2007)
Rating
Very nice routine. However, the spell check windows always goes UNDER my form the first time it is called. This makes the program appear to hang. Is there a way to get the spell check window to always appear on top?
Thanks
 
Comment #37  (Posted by Kei Matunaga on 04/22/2008)
Rating
Hi, it's a nice application. However, it seems that everytime we click on the spell checker (the spell checker window is active), and click on any other application, it will cause this application to hang.
Do you know how to avoid that?

Thanks!
 
Comment #38  (Posted by an unknown user on 07/12/2008)
Rating
I think it's a very bad idea to use the windows clipboard to pass in/out any data as the user does not like their clipbord to be overwritten. Why not just use the document's property "Content.Text" and simply add a TrimEnd when reading it back?
 
Comment #39  (Posted by an unknown user on 09/16/2008)
Rating
if richtext box contain an immage then this code does not work


image will be deleted
 
Comment #40  (Posted by an unknown user on 12/01/2008)
Rating
crelertr
 
Comment #41  (Posted by an unknown user on 12/08/2008)
Rating
Straightforward and easy. Suits my purpose down to the ground
 
Comment #42  (Posted by an unknown user on 04/28/2009)
Rating
When I hit this statement "ObjWord = New Word.Application()" I get this error: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005. How do I get around this?
 
Comment #43  (Posted by LesS on 04/28/2009)
Rating
When I hit this statement "ObjWord = New Word.Application()" I get this error: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005. How do I get around this?
 
Comment #44  (Posted by an unknown user on 05/31/2009)
Rating
It would be a natural place to indicate how to set the language.
 
Comment #45  (Posted by an unknown user on 06/12/2009)
Rating
Brilliant article. Thank you.
 
Comment #46  (Posted by an unknown user on 08/10/2009)
Rating
Thank you for the source code, was very useful
 
Comment #47  (Posted by an unknown user on 03/03/2010)
Rating
Great code. Thank you.
I just replaced the object declarations to enable intelliSense and option strict on.
Dim objWord As Microsoft.Office.Interop.Word.Application
Dim objTempDoc As Microsoft.Office.Interop.Word.Document
 
Comment #48  (Posted by Robert Wykoff on 03/12/2010)
Rating
I have figured out a simple way to do this with vb6, with the full formatting of the richtextbox remaining intact. This works for Word 2007, I do not know if it works for earlier versions

First in a module, put the following...

Global objWord As Object

Then put a button on the form with the rich text box with the following code...

Private Sub Command1_Click()

On Error GoTo ERRC

RichTextBox1.SaveFile ("C:\sc.rtf")
DoEvents

Set objWord = CreateObject("Word.basic")

objWord.fileopen "C:\sc.rtf"

objWord.StartOfDocument
objWord.EndOfDocument (1)
objWord.ToolsSpelling
objWord.filesave

DoEvents

' closes MS Word
objWord.FileClose (2)
objWord.FileQuit
Set objWord = Nothing

DoEvents
RichTextBox1.SetFocus

RichTextBox1.LoadFile ("C:\sc.rtf")
Exit Sub

ERRC:
Resume Next

End Sub


Walla, the full functionality of Microsoft Words spell checker updates a richtextbox with all formatting maintained
 
Comment #49  (Posted by an unknown user on 07/20/2010)
Rating
Limitations
Even though Spell-Checker Using Word will help you fulfill your basic spell-checking
needs in your ASP.NET applications, you should take a look at the following
limitations before considering a production level application development.
Microsoft Office Required: You need to install Microsoft Office on the server in
order to use the spell-checking functionality through its object model. Therefore you
need to acquire a license for Microsoft Office on your server.
Additional Coding Required: You need to write some code in your web pages in
order to open up the spell-check web form and pass in the identifier of the control
that contains the text to spell-check.
COM Interoperability: You need to create the Word application object using COM
Interoperability because there is no native .NET library provided for Word. This may
become an issue for garbage collection of those objects.
Scalability: You need to load the Word document object every time a new spellchecking
session is initiated. This may not scale well when you have a lot of users
connecting to website and running the spell-checker.
User Experience: It displays only the misspelled word without the context. This
makes it hard to figure out where the error is in the actual text. You should provide a
better user interface to show the misspelled word in the sentence or paragraph.
Page Refresh: Every time you click one of the buttons on the spell-check web form,
it refreshes the whole page because of the postback to server. This may not be an
issue for a short text, but it could be pretty annoying for a long text.
Custom Dictionary: Sometimes the user wants to add certain words into a custom
dictionary because they are not actually misspelled words. You may need to add a
new button on the form to let the user add a word to a custom dictionary at runtime.
 
Sponsored Links