VB.Net 藉由 Word 做拼字檢查 ( Check Spelling )

VB.Net 藉由 Word 做拼字檢查 ( Check Spelling )

VB.Net 藉由 Word 做拼字檢查 ( Check Spelling )

Imports System.Text

Imports System.Runtime.InteropServices

Public Class Form1

Private Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click

TextBox1.Text = CheckSpelling(TextBox1.Text)

End Sub

Private Sub Button2_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button2.Click

TextBox2.Text = ChkSpelling2(TextBox1.Text)

End Sub

' 方法1

Private Function CheckSpelling(ByVal word As String) As String

Const wdDialogToolsSpellingAndGrammar = 828 ' (&H33C)

Dim wd As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"))

wd.Visible = False

Dim doc As Object = wd.Documents.Add

wd.Selection.Text = word

wd.Dialogs(wdDialogToolsSpellingAndGrammar).Show()

CheckSpelling = wd.Selection.Text

doc.Close(0)

doc = Nothing

wd.Quit(0)

Marshal.ReleaseComObject(wd)

wd = Nothing

End Function

' 方法2

Private Function ChkSpelling2(ByVal word As String) As String ' Return Suggestion Word

Dim wd As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application"))

Dim sb As New StringBuilder

wd.Visible = False

wd.Documents.Add()

wd.ActiveDocument.Range.Text = word

wd.Options.CheckGrammarWithSpelling = True

wd.Options.SuggestSpellingCorrections = True

wd.CheckSpelling(word)

If wd.ActiveDocument.SpellingErrors.Count > 0 Then

lblStatus.Text = "單字錯誤!"

For Each Suggestion As Object In wd.GetSpellingSuggestions(word)

sb.AppendLine(Suggestion.Name)

Next

Else

lblStatus.Text = "單字正確!"

End If

wd.ActiveDocument.Close(0)

wd.Quit(0)

Marshal.ReleaseComObject(wd)

wd = Nothing

Return sb.ToString

End Function

End Class

拼字檢查 畫面1

拼字檢查 畫面2