如何:在 Word 和 .NET Framework 4 中使用自定义识别器创建智能标记

在面向 .NET Framework 4 的 Word 项目中,通过实现 ISmartTagExtension 接口,可以控制 Word 如何识别文档中的智能标记。

若要运行智能标记,最终用户必须在 Word 或 Excel 中启用智能标记。 有关更多信息,请参见如何:在 Word 和 Excel 中启用智能标记

**适用于:**本主题中的信息适用于 Word 2007 的文档级项目和应用程序级项目。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能

向 Word 文档添加具有自定义识别器的智能标记

  1. 为 Word 2007 创建一个文档级项目或应用程序级项目。 有关更多信息,请参见如何:在 Visual Studio 中创建 Office 项目

  2. 通过**“添加引用”对话框的“.NET”**选项卡添加对 Microsoft.Office.Interop.SmartTag 程序集(12.0.0.0 版)的引用。

  3. 向项目中添加类文件,并创建一个用于实现 ISmartTagExtension 接口的类。

  4. 在新类中,创建一个表示智能标记的 SmartTag 对象,并创建一个或多个表示智能标记操作的 Action 对象。 使用 Globals.Factory.CreateSmartTagGlobals.Factory.CreateAction 方法创建这些对象。

  5. 实现 Recognize 方法,并编写自己的自定义识别行为。

    实现必须调用 context 参数的 PersistTag 方法以使 Word 能够识别该智能标记。

  6. 实现 ExtensionBase 属性以返回 SmartTag 对象。

  7. 创建事件处理程序以响应所创建操作的 Click 事件和 BeforeCaptionShow 事件(后者可选)。

  8. 在项目文档的代码文件中,将该智能标记实例添加到 ThisDocument 类(对于文档级项目)的 VstoSmartTags 属性或 ThisAddIn 类(对于应用程序级项目)的 VstoSmartTags 属性中。

示例

下面的代码示例演示如何在 Word 文档中创建自定义智能标记。 该示例实现 Recognize 方法以识别术语 sales 和 organization。 Recognize 方法向智能标记的键属性集合中添加一个键/值对。 该方法随后调用 PersistTag 方法来识别该智能标记,并保存新的智能标记属性。

若要测试该示例,请在文档的不同位置键入单词 sales 和 organization,然后尝试执行智能标记操作。 其中一项操作显示与所识别的术语相应的属性值,另一项操作显示智能标记命名空间和标题。

Imports System
Imports System.Windows.Forms
Imports Microsoft.Office.Interop.SmartTag
Imports Microsoft.Office.Tools.Word

Public Class CustomSmartTag
    Implements ISmartTagExtension
    ' Declare the smart tag.
    Private smartTagDemo As Microsoft.Office.Tools.Word.SmartTag

    ' Declare actions for this smart tag.
    WithEvents Action1 As Microsoft.Office.Tools.Word.Action
    WithEvents Action2 As Microsoft.Office.Tools.Word.Action

    Public Sub New()
        Me.smartTagDemo = Globals.Factory.CreateSmartTag(
            "https://www.contoso.com/Demo#DemoSmartTag", "Custom Smart Tag", Me)

        Action1 = Globals.Factory.CreateAction("Display property value")
        Action2 = Globals.Factory.CreateAction("Display smart tag details")

        smartTagDemo.Terms.AddRange(New String() {"sales", "organization"})
        smartTagDemo.Actions = New Microsoft.Office.Tools.Word.Action() {Action1, Action2}

    End Sub

    Private Sub Recognize(ByVal text As String,
        ByVal site As ISmartTagRecognizerSite,
        ByVal tokenList As ISmartTagTokenList,
        ByVal context As SmartTagRecognizeContext) Implements ISmartTagExtension.Recognize

        For Each term As String In smartTagDemo.Terms
            ' Search the text for the current smart tag term.
            Dim index As Integer = text.IndexOf(term, 0)

            While (index >= 0)
                ' Create a smart tag token and a property bag for the recognized term.
                Dim propertyBag As ISmartTagProperties = site.GetNewPropertyBag()

                ' Write a new property value.
                Dim key As String = "Key1"
                propertyBag.Write(key, DateTime.Now.ToString())

                ' Attach the smart tag to the term in the document
                context.PersistTag(index, term.Length, propertyBag)

                ' Increment the index and then find the next instance of the smart tag term.
                index += term.Length
                index = text.IndexOf(term, index)
            End While
        Next
    End Sub

    ' This action displays the property value for the term.
    Private Sub Action1_Click(ByVal sender As Object,
        ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) Handles Action1.Click
        Dim propertyBag As ISmartTagProperties = e.Properties
        Dim key As String = "Key1"
        MessageBox.Show(("The corresponding value of " & key & " is: ") + propertyBag.Read(key))
    End Sub

    ' This action displays smart tag details.
    Private Sub Action2_Click(ByVal sender As Object,
        ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) Handles Action2.Click
        MessageBox.Show(("The current smart tag caption is '" &
            smartTagDemo.Caption & "'. The current smart tag type is '") &
            smartTagDemo.SmartTagType & "'.")
    End Sub

    Public ReadOnly Property Base() As Microsoft.Office.Tools.Word.SmartTag
        Get
            Return (smartTagDemo)
        End Get
    End Property

    Public ReadOnly Property ExtensionBase() As Object Implements ISmartTagExtension.ExtensionBase
        Get
            Return (smartTagDemo)
        End Get
    End Property
End Class
using System;
using System.Windows.Forms;
using Microsoft.Office.Interop.SmartTag;
using Microsoft.Office.Tools.Word;

namespace CustomSmartTagExample
{
    public class CustomSmartTag : ISmartTagExtension
    {
        // Declare the smart tag.
        Microsoft.Office.Tools.Word.SmartTag smartTagDemo;

        // Declare actions for this smart tag.
        private Microsoft.Office.Tools.Word.Action Action1;
        private Microsoft.Office.Tools.Word.Action Action2;

        public CustomSmartTag()
        {
            this.smartTagDemo = Globals.Factory.CreateSmartTag(
                "https://www.contoso.com/Demo#DemoSmartTag", "Custom Smart Tag", this);

            Action1 = Globals.Factory.CreateAction("Display property value");
            Action2 = Globals.Factory.CreateAction("Display smart tag details");

            smartTagDemo.Terms.AddRange(new string[] { "sales", "organization" });
            smartTagDemo.Actions = new Microsoft.Office.Tools.Word.Action[] { Action1, Action2 };

            Action1.Click += new ActionClickEventHandler(Action1_Click);
            Action2.Click += new ActionClickEventHandler(Action2_Click);
        }

        void ISmartTagExtension.Recognize(string text, ISmartTagRecognizerSite site, ISmartTagTokenList tokenList, 
            SmartTagRecognizeContext context)
        {

            foreach (string term in smartTagDemo.Terms)
            {
                // Search the text for the current smart tag term.
                int index = text.IndexOf(term, 0);

                while (index >= 0)
                {
                    // Create a smart tag token and a property bag for the recognized term.
                    ISmartTagProperties propertyBag = site.GetNewPropertyBag();

                    // Write a new property value.
                    string key = "Key1";
                    propertyBag.Write(key, DateTime.Now.ToString());

                    // Attach the smart tag to the term in the document
                    context.PersistTag(index, term.Length, propertyBag);

                    // Increment the index and then find the next instance of the smart tag term.
                    index += term.Length;
                    index = text.IndexOf(term, index);
                }
            }
        }

        // This action displays the property value for the term.
        private void Action1_Click(object sender,
            Microsoft.Office.Tools.Word.ActionEventArgs e)
        {
            ISmartTagProperties propertyBag = e.Properties;
            string key = "Key1";
            MessageBox.Show("The corresponding value of " + key + " is: " + propertyBag.get_Read(key));
        }

        // This action displays smart tag details.
        private void Action2_Click(object sender,
            Microsoft.Office.Tools.Word.ActionEventArgs e)
        {
            MessageBox.Show("The current smart tag caption is '" +
                smartTagDemo.Caption + "'. The current smart tag type is '" + smartTagDemo.SmartTagType + "'.");
        }


        public Microsoft.Office.Tools.Word.SmartTag Base
        {
            get { return smartTagDemo; }
        }

        public object ExtensionBase
        {
            get { return smartTagDemo; }
        }

    }
}

编译代码

  • 通过**“添加引用”对话框的“COM”选项卡在项目中添加对“Microsoft Smart Tags 2.0 类型库”的引用。 确保该引用的“复制本地”**属性为 false。 如果该属性为 true,则表示该引用不是正确的主互操作程序集,您必须从 Microsoft Office 安装媒体中安装该程序集。 有关更多信息,请参见如何:安装 Office 主互操作程序集

  • 将代码示例放入名为 CustomSmartTag 的新的类文件中。

  • 在 C# 中,将命名空间更改为与项目名称匹配。

  • 在类文件的顶部,为 Microsoft.Office.Tools.WordMicrosoft.Office.Interop.SmartTag 命名空间添加 Imports (Visual Basic) 或 using (C#) 语句。

  • 向项目的 ThisDocument_Startup 或 ThisAddIn_Startup 事件处理程序中添加以下代码。 此代码将向文档中添加自定义智能标记。

    Me.VstoSmartTags.Add(New CustomSmartTag().Base)
    
    this.VstoSmartTags.Add(new CustomSmartTag().Base);
    

安全性

若要运行智能标记,必须要在 Word 中启用智能标记。 有关更多信息,请参见如何:在 Word 和 Excel 中启用智能标记

请参见

任务

如何:在 Word 和 Excel 中启用智能标记

如何:向 Word 文档添加智能标记

如何:向 Excel 工作簿添加智能标记

如何:在 Excel 和 .NET Framework 3.5 中使用自定义识别器创建智能标记

演练:使用文档级自定义项创建智能标记

演练:使用应用程序级外接程序创建智能标记

概念

智能标记的结构

其他资源

智能标记概述