Introduction
Very often, when developing software, we have to include a spelling and grammar check function, and don't want to shell out the cash for a proprietary solution. We search the web and find ways to incorporate the MS Word interop capabilities - it always starts with, create a solution, add a reference.
Then, we build it and run it, and it works great. Then, we run it on someone else's computer who either doesn't have MS Word or has a different version, and we have all kinds of problems - assemblies not found in the GAC, etc. Why can't we add the reference at runtime so we can use any version of Word?
Using the System.Reflection
namespace, we can!
Background
You should be familiar with the MS Office interop services, see a few other spell check examples if you are not. Bits and pieces of this were inspired by other CodeProject articles, and it is covered much more in depth in them. This article will focus on doing the same thing, but with System.Reflection
rather than adding a reference ahead of time.
Using the code
To use the code, just call the Sub
and pass it a TextBox
.
There are two Imports
to be used...
Imports System.Runtime.InteropServices
Imports System.Reflection
and now the magic:
Private Sub SpellAndGrammarCheck(ByVal YourTextbox As TextBox)
Try
Dim objWord As Object = Nothing
Dim objDoc As Object = Nothing
Dim objData As IDataObject = Nothing
If YourTextbox.Text = "" Then
Exit Sub
End If
objWord = System.Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"))
Dim objDocuments As Object
objDocuments = objWord.[GetType]().InvokeMember("Documents", _
BindingFlags.[Default] Or BindingFlags.GetProperty, _
Nothing, objWord, Nothing)
objDoc = objDocuments.[GetType]().InvokeMember("Add", BindingFlags.[Default] _
Or BindingFlags.InvokeMethod, Nothing, objDocuments, Nothing)
objWord.Visible = False
objWord.WindowState = 0
objWord.Top = -3000
Clipboard.SetDataObject(YourTextbox.Text)
With objDoc
.Content.Paste()
.Activate()
.CheckGrammar()
.Content.Copy()
objData = Clipboard.GetDataObject
If objData.GetDataPresent(DataFormats.Text) Then
YourTextbox.Text = CType(objData.GetData(DataFormats.Text), String)
End If
.Saved = True
.Close()
End With
objWord.Quit()
SPELLWORKING = True
Catch COMEcep As COMException
MsgBox("MS Word must be installed to perform spelling checks", , _
"Spell check is not available")
SPELLWORKING = False
Catch ex As Exception
SPELLWORKING = False
MsgBox("Error, Make sure you have MS word installed.", , ex.Message)
End Try
Points of interest
I've had one instance of this causing a 'hang', but when the program restarted, it was fine... I've tested it with Word XP, 2003, and 2007. Hope it helps you!