samsmithnz
Well-known member
Im currently writing a windows application, and I want to have spell checking, so I am trying to use the Word spell checking. This is all working ok except that I am reading from a richtextbox, and for some reason, I cut and paste actual richtext into word, instead of the text. HEre is the function I am currently using: (its kind of long - sorry but easy to understand - its the part where you copy data into the document that I think needs a little tweak - any ideas? - you can see what Ive been trying...)
Code:
Invokes either the spell or grammar checker.
Public Function SpellOrGrammarCheck(ByVal blnSpellOnly As Boolean, ByVal strText As String) As String
Try
Create Word and temporary document objects.
Dim objWord As Microsoft.Office.Interop.Word.Application
Dim objTempDoc As Microsoft.Office.Interop.Word.Document
Dim iData As IDataObject Declare an IDataObject to hold the data returned from the clipboard.
Dim strResultString As String
If there is no data to spell check, then exit sub here.
If strText = "" Then
Exit Function
End If
objWord = New Microsoft.Office.Interop.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(strText)
With the temporary document, perform either a spell check or a complete grammar check, based on user selection.
With objTempDoc
METHOD 1: use the clipboard
.Content.Paste() PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdFormatOriginalFormatting)
METHOD 2: ignore the clipboard, cut and paste in the data directly...
.Range.Text = strText
.Activate()
If blnSpellOnly = True Then
.CheckSpelling()
Else
.CheckGrammar()
End If
METHOD 1 CONTINUED
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
strText = CType(iData.GetData(DataFormats.Text), String)
End If
METHOD 2 CONTINUED
strText = .Range.Text
.Saved = True
objWord.Visible = False This line of code keeps word hidden when saving...
.Close()
End With
Only quit word if there are no documents - so that this works with other documents open...
If objWord.Documents.Count = 0 Then
objWord.Quit()
End If
Return strText
MessageBox.Show(strResultString, "Spelling/Grammar Checker", MessageBoxButtons.OK, MessageBoxIcon.Information)
Microsoft Word must be installed.
Catch COMExcep As COMException
MessageBox.Show("Microsoft Word must be installed to use the Spelling/Grammar Check " & "to run.", "Spelling/Grammar Checker")
Catch Excep As Exception
MessageBox.Show("An error has occured.", "Spelling/Grammar Checker")
End Try
End Function