Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Studio .NET » Spell check enabled RichTextBox custom control

Spell check enabled RichTextBox custom control

This article describes a quick and simple approach to applying a spell check function to the rich text box control and bundling both features into a single custom control. Of course there is nothing novel or particularly interesting about performing spell checking upon a selection of text using the Word.DLL.

Author Rank:
Total page views :  27338
Total downloads :  1074
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SpellcheckCCpack.zip
 
Become a Sponsor


This article describes a quick and simple approach to applying a spell check function to the rich text box control and bundling both features into a single custom control. Of course there is nothing novel or particularly interesting about performing spell checking upon a selection of text using the Word.DLL, it has been done many times and there is nothing new here with regards to the details of the mechanization I've used other than the fact that it is all contained within a custom control.

My interest in building this control was two-fold; first I wanted the functionality placed into a custom control so that is might more easily be dropped into multiple locations in a form used to collect narrative information from the user, and the second element of interest was to answer the question as to whether or not the control would function on systems equipped with either Word 2003 or Word 2007.

With regards to the two versions of Word; I was able to run the control on systems equipped with either Microsoft Word 2003 or 2007 and on both Vista and XP. It does seem that an application built using the control will at least survive the transition from Microsoft Word 2003 to Microsoft Word 2007.

img1.jpg

Figure 1:  RTB with Spell Check Custom Control in Use

Getting Started
:

In order to get started, fire up the Visual Studio 2005 IDE and open the attached solution.  The solution consists of a Win Forms project with a single form and a control project containing a single custom control. The Win Forms project main form is used as a test bed for the custom control and the custom control is an extension of the standard windows forms rich text box control.  Figure 2 shows the solution explorer for this project, note the addition of the references to Microsoft Office contained in the control project:

Image2.jpg

Figure 2:  Solution Explorer

The Code:  Main Form

The main form of the application serves only as a test project for the Spell Check custom control; the project contains only a single form and that form contains only a toolbar and the custom control. The tool bar contains only the controls necessary to open or save a file from the extended rich text box control, to execute the command to spell check the contents of the rich text box, and to exit the application.

The code contained in the form follows; in imports are in the default configuration with one exception which was the addition of the System.IO library which is used to support opening and closing files. The namespace and class declarations are in the default configuration.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

 

namespace SpellCheck

{

    /// <summary>

    /// Demo of the use of the spell check custom control

    /// </summary>

    public partial class Form1 : Form

    {

 

The next section of code is used to declare a string variable used to contain the path to the current file. The constructor follows this variable declaration and it is in the default configuration.

 

       // String pointing the file path of the current file

        private string currentFile = string.Empty;


        public Form1()

        {

            InitializeComponent();

        }

 

The next section of code contained in the demo application is the click event handler used to command the custom control to execute the Check Spelling function.  This function will launch the Word based spell check function against the contents of the control's rich text box.

        // evoke the spell check function

        private void tspSpellCheck_Click(object sender, EventArgs e)

        {

            this.spellCheckTextControl1.CheckSpelling();

            this.Refresh();

        }

 

The next section of code in the demo project is used to save the contents of the control into a file.  There is nothing unique about how this save method works, it is based upon the use of a SaveFileDialog and relies upon the rich text box control's Save File method if the content is rich text. If the content is not rich text, it will be saved using the alternative method provided.

        // save the current file

        private void tspSave_Click(object sender, EventArgs e)

        {

            try

            {

                SaveFileDialog1.Title = "Save File";

                SaveFileDialog1.DefaultExt = "rtf";

                SaveFileDialog1.Filter = "Rich Text Files|*.rtf|Text

                Files|*.txt|HTML Files|*.htm|All Files|*.*";

                SaveFileDialog1.FilterIndex = 1;

 

                if (SaveFileDialog1.ShowDialog() == DialogResult.OK)

                {

 

                    if (SaveFileDialog1.FileName == "")

                    {

                        return;

                    }

 

                    string strExt;

                    strExt =

                    System.IO.Path.GetExtension(SaveFileDialog1.FileName);

                    strExt = strExt.ToUpper();

 

                    if (strExt == ".RTF")

                    {

                       spellCheckTextControl1.SaveFile

                       (SaveFileDialog1.FileName,

                        RichTextBoxStreamType.RichText);

                    }

                    else

                    {

                        System.IO.StreamWriter txtWriter;

                        txtWriter = new System.IO.StreamWriter

                        (SaveFileDialog1.FileName);

                        txtWriter.Write(spellCheckTextControl1.Text);

                        txtWriter.Close();

                        txtWriter = null;

                        spellCheckTextControl1.SelectionStart = 0;

                        spellCheckTextControl1.SelectionLength = 0;

                    }

 

                    currentFile = SaveFileDialog1.FileName;

                    spellCheckTextControl1.Modified = false;

                    MessageBox.Show(currentFile.ToString() + " saved.", "File

                    Save");

                }

                else

                {

                    MessageBox.Show("Save File request cancelled by user.",

                    "Cancelled");

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message.ToString(), "Error");

            }

        }

Following the Save button's click event handler, the piece of code is used to open a file into the rich text box control.  This operation is supported through the use of an open file dialog control.

        // open a file into the control

        private void tspOpen_Click(object sender, EventArgs e)

        {

            try

            {

                OpenFileDialog1.Title = "Open File";

                OpenFileDialog1.DefaultExt = "rtf";

                OpenFileDialog1.Filter = "Rich Text Files|*.rtf|Text

                Files|*.txt|HTML Files|*.htm|All Files|*.*";

                OpenFileDialog1.FilterIndex = 1;

                OpenFileDialog1.FileName = string.Empty;

 

                if (OpenFileDialog1.ShowDialog() == DialogResult.OK)

                {

 

                    if (OpenFileDialog1.FileName == "")

                    {

                        return;

                    }

 

                    string strExt;

                    strExt =

                    System.IO.Path.GetExtension(OpenFileDialog1.FileName);

                    strExt = strExt.ToUpper();

 

                    if (strExt == ".RTF")

                    {

                        spellCheckTextControl1.LoadFile

                        (OpenFileDialog1.FileName,

                        RichTextBoxStreamType.RichText);

                    }

                    else

                    {

                        System.IO.StreamReader txtReader;

                        txtReader = new System.IO.StreamReader

                        (OpenFileDialog1.FileName);

                        spellCheckTextControl1.Text = txtReader.ReadToEnd();

                        txtReader.Close();

                        txtReader = null;

                        spellCheckTextControl1.SelectionStart = 0;

                        spellCheckTextControl1.SelectionLength = 0;

                    }

 

                    currentFile = OpenFileDialog1.FileName;

                    spellCheckTextControl1.Modified = false;

                }

                else

                {

                    MessageBox.Show("Open File request cancelled by user.",

                    "Cancelled");

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message.ToString(), "Error");

            }

        }

The last bit of code in the demo is used to close the current form and terminate the application. 

 

        // exit

        private void tspExit_Click(object sender, EventArgs e)

        {

            this.Dispose();

        }

 

    }

}

That wraps up the discussion of the form based demo project.

The Code:  Spell Check Control

The Spell Check control is a custom control built to extend the standard Windows Forms Rich Text Box control; the only additions made to the standard control were to add those items necessary to implement the Word DLL spell check method against the rich text box control. The control also exposes a couple of properties used to configure the spell check control and to define part of the spell check dialog available functionality.

If you open the code up and examine the imports, you will note following imports prior to the namespace and class declaration.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using Microsoft.Office.Core;

using Microsoft.Office.Interop.Word;

 

namespace SpellCheckControl

{

    public partial class SpellCheckTextControl :

    System.Windows.Forms.RichTextBox

    {

After the class declaration; the code defines a region containing a collection of member variables used to support setting the control's properties and to configure the arguments passed to the check spelling function exposed by the Word.DLL; note that these variables are declared as objects; this is essential to working with the Word.DLL exposed check spelling argument list where all arguments are passed by reference as objects.

#region Member Variables

 

        private object emptyItem = System.Reflection.Missing.Value;

        private object oNothing = null;

        private object oTrue = true;

        private object oFalse = false;

        private object oAlwaysSuggest = true;

        private object oIgnoreUpperCase = false;

        private bool mAlwaysSuggest = true;

        private bool mIgnoreUpperCase = false;

 

#endregion

 

The control exposes two public properties, one is used to set the Word.DLL spell check method's Always Suggest option, and the other is used to set its Ignore Upper Case option.  In order work effectively in the IDE as design time; the type is set as a Boolean (both properties) but when the Boolean is set, a shadowing object is also set to equal true or false; it is the object and not the Boolean that is actually passed to the Word.DLL check spelling method.

The Word.DLL check spelling method would also permit the user to pass custom dictionaries to it through additional arguments; in this example, I did not expose any properties to include any custom dictionaries however, using the same approach, one could pass in these alternative custom dictionaries.   

#region Properties
 

        public bool AlwaysSuggest

        {

            get

            {

                return mAlwaysSuggest;

            }

            set

            {

                mAlwaysSuggest = value;

 

                if (mAlwaysSuggest == true)

                    oAlwaysSuggest = true;

                else

                    oAlwaysSuggest = false;

            }

        } 

 

        public bool IgnoreUpperCase

        {

            get

            {

                return mIgnoreUpperCase;

            }

            set

            {

                mIgnoreUpperCase = value;

 

                if (mIgnoreUpperCase == true)

                    oIgnoreUpperCase = true;

                else

                    oIgnoreUpperCase = false;

            }

        }

 

#endregion

 

The following code covers the control's default constructor and On Paint method:

#region Constructor and Defaults

 

    public SpellCheckTextControl()

    {

        InitializeComponent();

    }

 

    protected override void OnPaint(PaintEventArgs pe)

    {

        base.OnPaint(pe);

    }

 

#endregion

The next bit of code is that which is required to perform the actual spell check function based upon the use of the Word.DLL. This section of code is annotated to describe the content.      

#region Perform Spell Check

 

        /// <summary>

        /// Perform spell check operation on control content.

        /// This operation displays the results of the spell

        /// check. 

        ///

        /// Alternatively, the function could be set to return

        /// a string and the results string could be returned

        /// to the caller

        /// </summary>

        public void CheckSpelling()

        {

 

            // declare local variables to track error count

            // and information

            int SpellingErrors = 0;

            string ErrorCountMessage = string.Empty;

 

            // create an instance of a word application

            Microsoft.Office.Interop.Word.Application WordApp =

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

 

            // hide the MS Word document during the spellcheck

            WordApp.Visible = false;

            WordApp.ShowWindowsInTaskbar = false;

 

            // check for zero length content in text area

            if (this.Text.Length > 0)

            {
 

                // create an instance of a word document

                _Document WordDoc = WordApp.Documents.Add(ref emptyItem,

                                                  ref emptyItem,

                                                  ref emptyItem,

                                                  ref oFalse);

 

                // load the content written into the word doc

                WordDoc.Words.First.InsertBefore(this.Text);

 

                // collect errors form new temporary document set to contain

                // the content of this control

                Microsoft.Office.Interop.Word.ProofreadingErrors docErrors =

                WordDoc.SpellingErrors;

                SpellingErrors = docErrors.Count;

 

                // execute spell check; assumes no custom dictionaries

                WordDoc.CheckSpelling(ref oNothing, ref oIgnoreUpperCase, ref

                    oAlwaysSuggest,ref oNothing, ref oNothing, ref oNothing,

                    ref oNothing, ref oNothing,

                    ref oNothing, ref oNothing, ref oNothing, ref oNothing);

 

                // format a string to contain a report of the errors detected

                ErrorCountMessage = "Spell check complete; errors detected: "

                + SpellingErrors;

 

                // return corrected text to control's text area

                object first = 0;

                object last = WordDoc.Characters.Count - 1;

                this.Text = WordDoc.Range(ref first, ref last).Text;

            }

            else

            {

                // if nothing was typed into the control, abort and inform

                // user

                ErrorCountMessage = "Unable to spell check an empty text

                box.";

            }

 

            WordApp.Quit(ref oFalse, ref emptyItem, ref emptyItem);

 

            // return report on errors corrected

            // - could either display from the control or change this to

            // - return a string which the caller could use as desired.

            MessageBox.Show(ErrorCountMessage, "Finished Spelling Check");

        }

 

#endregion

At design time, the control user may set properties in the property grid, or the values may be set in the code.

Image4.jpg

Figure 3:  Property for "Always Suggest" Option

Summary

This article described an approach to creating a text input control capable of checking the spelling contained in the text area of the control. The control is an extended version of the rich text box control and relies upon the Word.DLL check spelling function in order to support internal spell checking. The control may be useful if one were capturing free text entries from a user  and it was deemed desirable to check the content of those free text entries for misspellings.


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SpellcheckCCpack.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
spell check in rich text box by juan On June 15, 2007
will this work on a web app text box ?
Reply | Email | Delete | Modify | 
Re: spell check in rich text box by Scott On June 16, 2007

I have not tried it but it should be possible; it would work at least in IE if you wrapped it up as a custom control.

You might want to look at something like this instead though:

http://www.iespell.com/

 

Reply | Email | Delete | Modify | 
will this work on a web app? by Diego Enrique On August 9, 2007
Hello, this won't work on a web app because you can't use Interop with office on a web app, Interop needs hight user rights that a web app hasn't, one idea may be to create a remoting app, this app provides the spell check service using Word interop, this remoting app should run on a user account with enought rights to run Interop, from your web app you invoke this remoting service and get the spell check. You could launch the remoting app in an automatic way using a windows service. Another idea is to get a spell check component that supports ASP.Net, check http://www.tachyon-labs.com/sharpspell.aspx Diego Mesa Tabares MCP
Reply | Email | Delete | Modify | 
sql installation errors by venkat On March 16, 2010
when i am trying to install sql server 2008 in my computer, it is giving invalid login or unauthorized use errors

hot to solve send me to venkatfuture@yahoo.com
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.