65.9K
CodeProject 正在变化。 阅读更多。
Home

无需提前添加引用即可在 .NET 中进行拼写检查 - 版本无关!

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.07/5 (6投票s)

2008年9月12日

CPOL

1分钟阅读

viewsIcon

36131

通过任何版本的 Word 在您的 .NET 应用程序中运行拼写检查,而无需在设计时进行引用。

引言

在开发软件时,我们经常需要包含拼写和语法检查功能,并且不想花钱购买专有解决方案。我们搜索网络,找到使用 MS Word interop 功能的方法——它总是从创建一个解决方案,添加一个引用开始。

然后,我们构建并运行它,一切正常。然后,我们在别人的计算机上运行它,而对方可能没有安装 MS Word,或者安装了不同的版本,我们就会遇到各种问题——程序集未在 GAC 中找到等等。为什么我们不能在运行时添加引用,以便使用任何版本的 Word 呢?

使用 System.Reflection 命名空间,我们可以!

背景

您应该熟悉 MS Office interop 服务,如果您不熟悉,请参阅其他一些拼写检查示例。这篇文章的灵感来自其他 CodeProject 文章的片段,并且在这些文章中得到了更深入的介绍。本文将重点介绍使用 System.Reflection 而不是提前添加引用来做同样的事情。

使用代码

要使用此代码,只需调用 Sub 并传递一个 TextBox 即可。

需要使用两个 Imports...

Imports System.Runtime.InteropServices 
Imports System.Reflection

现在开始实现魔法

Private Sub SpellAndGrammarCheck(ByVal YourTextbox As TextBox)

    Try
        'Rather than giving it a type right now, we just give 
        'it generic object status - same below 
        Dim objWord As Object = Nothing
        Dim objDoc As Object = Nothing
        Dim objData As IDataObject = Nothing

        If YourTextbox.Text = "" Then
        ' if there's nothing in your textbox, there's nothign to do
            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()
            ' MsgBox("Spelling check complete!")
            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

关注点

我遇到过一次此代码导致“挂起”的情况,但程序重启后一切正常……我已使用 Word XP、2003 和 2007 对其进行了测试。希望对您有所帮助!

© . All rights reserved.