[
Advertise | Submit Code | About us | Contact us | Link us
]
Go!
Membership Services
Login
Register

Home
C# General

General

C# Language

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting
C# Windows Forms

General

Combo and List boxes

Miscellaneous Controls

Button Controls

Edit Controls
Cutting Edge

ASP.NET 2.0

Visual Studio 2005

Windows Longhorn

SQL Server 2005
C# Multimedia and GDI+

General

DirectX

GDI+

Audio
Internet & Web

General

Images and multimedia

Database

Utilities

Security

ASP.NET Controls

Design and Architecture

Webservices
.NET

General

Design & Architecture

Algorithms

Database

Security

Active Directory

COM Interop

Remoting

ADO.NET

XML.NET

Tools

Enterprise

IDE
Visual Basic .NET

VB.NET General

VB.NET Controls
General Reading

.NET Books Review

Product Showcase

Book Chapters

Business Design & Strategy
Community

Discuss

Job Board

Discussion

CodeXchange
DeveloperLand

Advertise

Submit Code

About us

Contact us

Link us
Miscellaneous

Favorite Links

Downloads

Programming Sites

Top Stories
Regular Expressions

E-Mail

Date/Time
Home > Visual Basic .NET > VB.NET General
Adding Spelling and Grammar Checking Functions into VB.NET Applications
Posted by on Sunday, October 17, 2004 (EST)

Many applications can be enhanced by including spelling and grammar checking capabilities.This article will demonstrate how to add these functions to a Visual Basic.NET Windows Form project

This article has been viewed: 4,553 times
Technology: VB.NET General.

spellcheck.zip (405.92 KB)

Contents

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:

Type Name Text
Button btnSpellCheck Spell Check
Button btnGrammarCheck Grammar Check
Textbox Textbox1  

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.

Top Go to Table of Contents

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.Text) Then
                    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.EventArgs) Handles btnSpellCheck.Click
        SpellOrGrammarCheck(True)
    End Sub
    Private Sub btnGrammarCheck_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnGrammarCheck.Click
        SpellOrGrammarCheck(False)
    End Sub

Top Go to Table of Contents

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.Text) Then
                    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.EventArgs) Handles btnSpellCheck.Click
        SpellOrGrammarCheck(True)
    End Sub
    Private Sub btnGrammarCheck_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnGrammarCheck.Click
        SpellOrGrammarCheck(False)
    End Sub
End Class

Top Go to Table of Contents

About David Wasserman

Click here if you want to know more about .

Other articles that may interest you

  • Write a Word Add-In – Part 0
  • Write a Word Add-In – Part I
  • Lengthy Operations on Single Thread in .NET Application
  • Learning Draughts
  • Exceptions and Performance
  • Average Rating :

    Discussion Forums
    Got a programming related question? Hopefully someone has the answer... Want to help out other developers? Visit our discussion forums.

    Sponsored by:

    New Articles

  • Exceptions and Performance
    Almost every time exceptions are mentioned in mailing lists and newsgroups, people say they're really expensive.Let's examine that claim, shall we?

  • Creating multilingual websites - Part 1
    Extend the existing globalization capabilities of .NET to create flexible and powerful multilingual web sites. First, create a custom ResourceManager, and then create custom localized-capable server controls to easily deploy multilingual functionality.

  • Parameter passing in C#
    Many people have become fairly confused about how parameters are passed in C#, particularly with regard to reference types. This page should help to clear up some of that confusion

  • Most Popular Articles

  • LDAP, IIS and WinNT Directory Services
    This article explains how to use .NET Directory Services to retrieve and search directory objects, create new directory objects and edit or delete existing directory objects. Describes Active Directory Application Mode (ADAM) and how to use the IIS, WinNT and LDAP directory (ADSI) provider.

  • An in-depth look at WMI and instrumentation, Part II
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article is the second part of a two-part series.

  • An in-depth look at WMI and instrumentation, Part I
    WMI stands for Windows Management Instrumentation and, as the name indicates, is about managing your IT infrastructure this article provides an in-depth look at WMI and MOM 2005

  • New Books

  • Murach's ASP.NET 2.0 Upgrader's Guide: VB Edition
    What’s new and how to use it! That’s what this book delivers if you’re a VB developer who’s interested in upgrading from ASP.NET 1.x to ASP.NET 2.0.

  • C# in easy steps
    Learn to program with Microsoft’s premier programming language. No previous programming knowledge is assumed. With numerous easy-to-follow examples, this title explains the essentials of object-oriented programming with C#.

  • Murach's ASP.NET web programming with VB.NET
    Murach's ASP.NET web programming with VB.NET by Doug Lowe and Anne Prince is a in depth training and reference book for ASP.NET programming using VB.NET. The book builds upon Murach's previous books and covers more advanced concepts for programming ASP.NET pages.

  • Got Code?

    if you have any article , source code , or anything else you'd like to share with this community that you think others might find useful, please submit it here and we will gladly make it available on this site. submit@developerland.com.
    Partners

    All articles are copyrighted by their individual authors unless otherwise specified , everything else Copyright ©2004-2006 DeveloperLand