要使用Microsoft Word对象的属性和方法,需要引用Word组件。在解决方案浏览器中的“引用”上单击右键,添加引用,在弹出的对话框的标签页中选“COM”标签页,然后找到“Microsoft Word 9.0 Object Library”并双击它,单击“确定”按钮即可。注意:根据Microsoft Word版本的不同,Microsoft Word 9.0 Object Library中数字是不同的,这是Word 2000的版本号
Sub SpellOrGrammarCheck(ByVal blnSpellOnly As Boolean)
Try
' 创建Word对象和临时文档
Dim wdApp As Word.Application = New Word.Application
Dim wdDoc As Word.Document = wdApp.Documents.Add
' 声明IDataObject存放从剪贴板返回的数据
Dim iData As IDataObject
' 定位 Word 窗口,使之不可见
wdApp.WindowState = 0
wdApp.Top = -3000
' 复制输入框的文字到剪贴板
Clipboard.SetDataObject(txtWords.Text)
' 对临时文档进行拼写或者语法检查
With wdDoc
.Content.Paste()
.Activate()
If blnSpellOnly Then
.CheckSpelling() '拼写检查
'Else
.CheckGrammar() '语法检查同时进行拼写检查
End If
' 在拼写检查或者语法检查后,如果用户进行了修改,
'利用剪贴板把修改后的数据返回给文本输入框
.Content.Copy()
iData = Clipboard.GetDataObject()
If iData.GetDataPresent(DataFormats.Text) Then
txtWords.Text = CType(iData.GetData(DataFormats.Text), String)
End If
.Saved = True
.Close()
End With
wdApp.Quit()
MessageBox.Show("拼写检查已经完成!", "拼写检查", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch COMExcep As Runtime.InteropServices.COMException
MessageBox.Show("必须安装Microsoft Word才能进行拼写或者语法检查。", "拼写检查", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Catch Excep As Exception
MessageBox.Show("错误:" + Excep.Message, "拼写检查", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub