Cómo: Agregar etiquetas inteligentes a documentos de Word

Puede agregar etiquetas inteligentes a documentos de Microsoft Office Word para reconocer el texto y proporcionar al usuario acceso a las acciones relacionadas con las condiciones reconocidas. El código que se escribe para crear y configurar una etiqueta inteligente es el mismo para los proyectos en el nivel del documento y en el nivel de la aplicación, aunque existen algunas diferencias en la manera de asociar una etiqueta inteligente a los documentos. El ámbito de la etiquetas inteligentes también varía entre los proyectos en el nivel del documento y los proyectos en el nivel de la aplicación.

Se aplica a: la información de este tema se aplica a los proyectos de nivel de documento y los proyectos de nivel de aplicación para Word 2007. Para obtener más información, vea Características disponibles por aplicación y tipo de proyecto de Office.

En este tema se describen las tareas siguientes:

  • Agregar una etiqueta inteligente utilizando una personalización en el nivel del documento

  • Agregar una etiqueta inteligente utilizando un complemento en el nivel de la aplicación

Para ejecutar una etiqueta inteligente, los usuarios finales deben tener las etiquetas inteligentes habilitadas en Word o en Excel. Para obtener más información, vea Cómo: Habilitar las etiquetas inteligentes en Word y en Excel.

Agregar una etiqueta inteligente utilizando una personalización en el nivel del documento

Las etiquetas inteligentes de las personalizaciones en el nivel del documento sólo se reconocen en el documento que está asociado a la personalización.

Para agregar una etiqueta inteligente utilizando una personalización en el nivel del documento

  1. Cree un objeto SmartTag y configúrelo para definir el comportamiento de la etiqueta inteligente:

    • Para especificar el texto que desee reconocer, utilice la propiedad Terms o Expressions.

    • Para definir las acciones de la etiqueta inteligente en las que los usuarios pueden hacer clic, agregue uno o varios objetos Action a la propiedad Actions.

    Para obtener más información, vea Arquitectura de las etiquetas inteligentes.

  2. Agregue el objeto SmartTag a la propiedad VstoSmartTags de la clase ThisDocument.

En el ejemplo de código siguiente, se crea una etiqueta inteligente que reconoce las palabras term y recognize. Cuando el usuario hace clic en la etiqueta inteligente, se muestra la posición de los caracteres inicial y final de la palabra reconocida. Para ejecutar este código, agréguelo a la clase ThisDocument y, a continuación, llame al método AddSmartTag desde el controlador de eventos ThisDocument_Startup.

Nota

El siguiente ejemplo funciona en proyectos destinados a .NET Framework 4. Para usar este ejemplo en proyectos destinados a .NET Framework 3.5, vea los comentarios del código.

Private WithEvents displayAddress As Microsoft.Office.Tools.Word.Action

Private Sub AddSmartTag()

    ' Create the smart tag for .NET Framework 4 projects.
    Dim smartTagDemo As Microsoft.Office.Tools.Word.SmartTag = Globals.Factory.CreateSmartTag(
        "www.microsoft.com/Demo#DemoSmartTag",
        "Demonstration Smart Tag")

    ' For .NET Framework 3.5 projects, use the following code to create the smart tag.
    ' Dim smartTagDemo As New  _
    '     Microsoft.Office.Tools.Word.SmartTag( _
    '     "www.microsoft.com/Demo#DemoSmartTag", _
    '     "Demonstration Smart Tag")

    ' Specify the terms to recognize.
    smartTagDemo.Terms.Add("term")
    smartTagDemo.Terms.Add("recognize")

    ' Create the action for .NET Framework 4 projects.
    displayAddress = Globals.Factory.CreateAction("To be replaced")

    ' For .NET Framework 3.5 projects, use the following code to create the action.
    ' displayAddress = New Microsoft.Office.Tools.Word.Action("To be replaced")

    ' Add the action to the smart tag.
    smartTagDemo.Actions = New Microsoft.Office.Tools.Word.Action() { _
            displayAddress}

    ' Add the smart tag.
    Me.VstoSmartTags.Add(smartTagDemo)
End Sub

Private Sub DisplayAddress_BeforeCaptionShow(ByVal sender As Object, _
    ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) _
    Handles displayAddress.BeforeCaptionShow

    Dim clickedAction As Microsoft.Office.Tools.Word.Action = _
        TryCast(sender, Microsoft.Office.Tools.Word.Action)

    If clickedAction IsNot Nothing Then
        clickedAction.Caption = "Display the location of " & e.Text
    End If
End Sub

Private Sub DisplayAddress_Click(ByVal sender As Object, _
    ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) _
    Handles displayAddress.Click

    Dim termStart As Integer = e.Range.Start
    Dim termEnd As Integer = e.Range.End
    MsgBox("The recognized text '" & e.Text & _
            "' begins at position " & termStart & _
            " and ends at position " & termEnd)
End Sub
private Microsoft.Office.Tools.Word.Action displayAddress;

private void AddSmartTag()
{
    // Create the smart tag for .NET Framework 4 projects.
    Microsoft.Office.Tools.Word.SmartTag smartTagDemo =
        Globals.Factory.CreateSmartTag(
        "www.microsoft.com/Demo#DemoSmartTag",
        "Demonstration Smart Tag");

    // For .NET Framework 3.5 projects, use the following code to create the smart tag.
    // Microsoft.Office.Tools.Word.SmartTag smartTagDemo =
        // new Microsoft.Office.Tools.Word.SmartTag(
        //     "www.microsoft.com/Demo#DemoSmartTag",
        //     "Demonstration Smart Tag");

    // Specify the terms to recognize.
    smartTagDemo.Terms.Add("term");
    smartTagDemo.Terms.Add("recognize");

    // Create the action for .NET Framework 4 projects.
    displayAddress = Globals.Factory.CreateAction("To be replaced"); 

    // For .NET Framework 3.5 projects, use the following code to create the action.
    // displayAddress = new Microsoft.Office.Tools.Word.Action("To be replaced");

    // Add the action to the smart tag.
    smartTagDemo.Actions = new Microsoft.Office.Tools.Word.Action[] { 
        displayAddress };

    // Add the smart tag.
    this.VstoSmartTags.Add(smartTagDemo);

    displayAddress.BeforeCaptionShow += new
        Microsoft.Office.Tools.Word.BeforeCaptionShowEventHandler(
        displayAddress_BeforeCaptionShow);

    displayAddress.Click += new
        Microsoft.Office.Tools.Word.ActionClickEventHandler(
        displayAddress_Click);
}

void displayAddress_BeforeCaptionShow(object sender,
    Microsoft.Office.Tools.Word.ActionEventArgs e)
{
    Microsoft.Office.Tools.Word.Action clickedAction =
        sender as Microsoft.Office.Tools.Word.Action;

    if (clickedAction != null)
    {
        clickedAction.Caption = "Display the location of " +
            e.Text;
    }
}

void displayAddress_Click(object sender,
    Microsoft.Office.Tools.Word.ActionEventArgs e)
{
    int termStart = e.Range.Start;
    int termEnd = e.Range.End;
    System.Windows.Forms.MessageBox.Show("The recognized text '" + e.Text +
        "' begins at position " + termStart.ToString() +
        " and ends at position " + termEnd.ToString());
}

Agregar una etiqueta inteligente utilizando un complemento en el nivel de la aplicación

Al agregar una etiqueta inteligente mediante un complemento de nivel de aplicación, puede especificar si la etiqueta inteligente debe funcionar solo en un documento concreto o en todos los documentos abiertos (lo que se conoce como etiqueta inteligente de nivel de aplicación).

Para agregar una etiqueta inteligente a un documento concreto

  1. Cree un objeto SmartTag y configúrelo para definir el comportamiento de la etiqueta inteligente:

    • Para especificar el texto que desee reconocer, utilice la propiedad Terms o Expressions.

    • Para definir las acciones de la etiqueta inteligente en las que los usuarios pueden hacer clic, agregue uno o varios objetos Action a la propiedad Actions.

    Para obtener más información, vea Arquitectura de las etiquetas inteligentes.

  2. Para crear un elemento host Microsoft.Office.Tools.Word.Document para el documento que hospedará la etiqueta inteligente, use el método GetVstoObject. Para obtener más información sobre la creación de elementos host, vea Ampliar documentos de Word y libros de Excel en complementos en el nivel de la aplicación en tiempo de ejecución.

  3. Agregue el objeto SmartTag a la propiedad VstoSmartTags de Microsoft.Office.Tools.Word.Document.

El ejemplo de código siguiente crea una etiqueta inteligente en el documento activo que reconoce las palabras term y recognize. Cuando el usuario hace clic en la etiqueta inteligente, se muestra la posición de los caracteres inicial y final de la palabra reconocida. Para ejecutar este código, agréguelo a la clase ThisAddIn, llame al método AddSmartTagToDocument desde el controlador de eventos ThisAddIn_Startup y pase Microsoft.Office.Interop.Word.Document a AddSmartTagToDocument.

Nota

El siguiente ejemplo funciona en proyectos destinados a .NET Framework 4. Para usar este ejemplo en proyectos destinados a .NET Framework 3.5, vea los comentarios del código.

Private WithEvents displayAddress As Microsoft.Office.Tools.Word.Action

Private Sub AddSmartTagToDocument(ByVal document As Word.Document)
    ' Create a smart tag for .NET Framework 3.5 projects.
    ' Dim smartTagDemo As New  _
    '    Microsoft.Office.Tools.Word.SmartTag( _
    '    "www.microsoft.com/Demo#DemoSmartTag", _
    '    "Demonstration Smart Tag")
    ' Create a smart tag for .NET Framework 4 projects.
    Dim  smartTagDemo As SmartTag = Globals.Factory.CreateSmartTag(
        "www.microsoft.com/Demo#DemoSmartTag",
        "Demonstration Smart Tag")

    ' Specify the terms to recognize.
    smartTagDemo.Terms.Add("term")
    smartTagDemo.Terms.Add("recognize")

    ' Create the action for .NET Framework 3.5 projects.
    ' displayAddress = New Microsoft.Office.Tools.Word.Action("To be replaced")
    ' Create the action for .NET Framework 4 projects.
    displayAddress = Globals.Factory.CreateAction("To be replaced")

    ' Add the action to the smart tag.
    smartTagDemo.Actions = New Microsoft.Office.Tools.Word.Action() { _
            displayAddress}

    ' Get a Document host item for .NET Framework 3.5
    ' Dim vstoDocument As Microsoft.Office.Tools.Word.Document = _
    ' document.GetVstoObject()
    ' Get a Document host item for .NET Framework 4
    Dim vstoDocument As Microsoft.Office.Tools.Word.Document = _
        Globals.Factory.GetVstoObject(document)

    ' Add the smart tag to the document.
    vstoDocument.VstoSmartTags.Add(smartTagDemo)
End Sub

Private Sub DisplayAddress_BeforeCaptionShow(ByVal sender As Object, _
    ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) _
    Handles displayAddress.BeforeCaptionShow

    Dim clickedAction As Microsoft.Office.Tools.Word.Action = _
        TryCast(sender, Microsoft.Office.Tools.Word.Action)

    If clickedAction IsNot Nothing Then
        clickedAction.Caption = "Display the location of " & e.Text
    End If
End Sub

Private Sub DisplayAddress_Click(ByVal sender As Object, _
    ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) _
    Handles displayAddress.Click

    Dim termStart As Integer = e.Range.Start
    Dim termEnd As Integer = e.Range.End
    MsgBox("The recognized text '" & e.Text & _
            "' begins at position " & termStart & _
            " and ends at position " & termEnd)
End Sub
private Microsoft.Office.Tools.Word.Action displayAddress;

private void AddSmartTagToDocument(Word.Document document)
{
    Microsoft.Office.Tools.Word.SmartTag smartTagDemo =
        // Create a smart tag for .NET Framework 3.5 projects.
        //    new Microsoft.Office.Tools.Word.SmartTag(
        //    "www.microsoft.com/Demo#DemoSmartTag",
        //    "Demonstration Smart Tag");
        // Create a smart tag for .NET Framework 4 projects.
        Globals.Factory.CreateSmartTag(
            "www.microsoft.com/Demo#DemoSmartTag",
            "Demonstration Smart Tag");

    // Specify the terms to recognize.
    smartTagDemo.Terms.Add("term");
    smartTagDemo.Terms.Add("recognize");

    // Create the action for .NET Framework 3.5 projects.
    // displayAddress = new Microsoft.Office.Tools.Word.Action("To be replaced");
    // Create the action for .NET Framework 4 projects.
    displayAddress = Globals.Factory.CreateAction("To be replaced");

    // Add the action to the smart tag.
    smartTagDemo.Actions = new Microsoft.Office.Tools.Word.Action[] { 
        displayAddress };

    // Get a Document host item for .NET Framework 3.5
    // Microsoft.Office.Tools.Word.Document vstoDocument =
    //    document.GetVstoObject();
    // Get a Document host item for .NET Framework 3.5
    Microsoft.Office.Tools.Word.Document vstoDocument =
        Globals.Factory.GetVstoObject(document);
    // Add the smart tag to the document
    vstoDocument.VstoSmartTags.Add(smartTagDemo);

    displayAddress.BeforeCaptionShow += new
        Microsoft.Office.Tools.Word.BeforeCaptionShowEventHandler(
        displayAddress_BeforeCaptionShow);

    displayAddress.Click += new
        Microsoft.Office.Tools.Word.ActionClickEventHandler(
        displayAddress_Click);
}


void displayAddress_BeforeCaptionShow(object sender,
    Microsoft.Office.Tools.Word.ActionEventArgs e)
{
    Microsoft.Office.Tools.Word.Action clickedAction =
        sender as Microsoft.Office.Tools.Word.Action;

    if (clickedAction != null)
    {
        clickedAction.Caption = "Display the location of " +
            e.Text;
    }
}

void displayAddress_Click(object sender,
    Microsoft.Office.Tools.Word.ActionEventArgs e)
{
    int termStart = e.Range.Start;
    int termEnd = e.Range.End;
    System.Windows.Forms.MessageBox.Show("The recognized text '" + e.Text +
        "' begins at position " + termStart.ToString() +
        " and ends at position " + termEnd.ToString());
}

Para agregar una etiqueta inteligente que funcione en todos los documentos abiertos

  1. Cree un objeto SmartTag y configúrelo para definir el comportamiento de la etiqueta inteligente:

    • Para especificar el texto que desee reconocer, utilice la propiedad Terms o Expressions.

    • Para definir las acciones de la etiqueta inteligente en las que los usuarios pueden hacer clic, agregue uno o varios objetos Action a la propiedad Actions.

    Para obtener más información, vea Arquitectura de las etiquetas inteligentes.

  2. Agregue el objeto SmartTag a la propiedad VstoSmartTags de la clase ThisAddIn.

En el ejemplo de código siguiente, se crea una etiqueta inteligente que reconoce las palabras term y recognize. Cuando el usuario hace clic en la etiqueta inteligente, se muestra la posición de los caracteres inicial y final de la palabra reconocida. Para ejecutar este código, agréguelo a la clase ThisAddIn y, a continuación, llame al método AddSmartTag desde el controlador de eventos ThisAddIn_Startup.

Nota

El siguiente ejemplo funciona en proyectos destinados a .NET Framework 4. Para usar este ejemplo en proyectos destinados a .NET Framework 3.5, vea los comentarios del código.

Private WithEvents displayAddress As Microsoft.Office.Tools.Word.Action

Private Sub AddSmartTag()

    ' Create the smart tag for .NET Framework 4 projects.
    Dim smartTagDemo As Microsoft.Office.Tools.Word.SmartTag = Globals.Factory.CreateSmartTag(
        "www.microsoft.com/Demo#DemoSmartTag",
        "Demonstration Smart Tag")

    ' For .NET Framework 3.5 projects, use the following code to create the smart tag.
    ' Dim smartTagDemo As New  _
    '     Microsoft.Office.Tools.Word.SmartTag( _
    '     "www.microsoft.com/Demo#DemoSmartTag", _
    '     "Demonstration Smart Tag")

    ' Specify the terms to recognize.
    smartTagDemo.Terms.Add("term")
    smartTagDemo.Terms.Add("recognize")

    ' Create the action for .NET Framework 4 projects.
    displayAddress = Globals.Factory.CreateAction("To be replaced")

    ' For .NET Framework 3.5 projects, use the following code to create the action.
    ' displayAddress = New Microsoft.Office.Tools.Word.Action("To be replaced")

    ' Add the action to the smart tag.
    smartTagDemo.Actions = New Microsoft.Office.Tools.Word.Action() { _
            displayAddress}

    ' Add the smart tag.
    Me.VstoSmartTags.Add(smartTagDemo)
End Sub

Private Sub DisplayAddress_BeforeCaptionShow(ByVal sender As Object, _
    ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) _
    Handles displayAddress.BeforeCaptionShow

    Dim clickedAction As Microsoft.Office.Tools.Word.Action = _
        TryCast(sender, Microsoft.Office.Tools.Word.Action)

    If clickedAction IsNot Nothing Then
        clickedAction.Caption = "Display the location of " & e.Text
    End If
End Sub

Private Sub DisplayAddress_Click(ByVal sender As Object, _
    ByVal e As Microsoft.Office.Tools.Word.ActionEventArgs) _
    Handles displayAddress.Click

    Dim termStart As Integer = e.Range.Start
    Dim termEnd As Integer = e.Range.End
    MsgBox("The recognized text '" & e.Text & _
            "' begins at position " & termStart & _
            " and ends at position " & termEnd)
End Sub
private Microsoft.Office.Tools.Word.Action displayAddress;

private void AddSmartTag()
{
    // Create the smart tag for .NET Framework 4 projects.
    Microsoft.Office.Tools.Word.SmartTag smartTagDemo =
        Globals.Factory.CreateSmartTag(
        "www.microsoft.com/Demo#DemoSmartTag",
        "Demonstration Smart Tag");

    // For .NET Framework 3.5 projects, use the following code to create the smart tag.
    // Microsoft.Office.Tools.Word.SmartTag smartTagDemo =
        // new Microsoft.Office.Tools.Word.SmartTag(
        //     "www.microsoft.com/Demo#DemoSmartTag",
        //     "Demonstration Smart Tag");

    // Specify the terms to recognize.
    smartTagDemo.Terms.Add("term");
    smartTagDemo.Terms.Add("recognize");

    // Create the action for .NET Framework 4 projects.
    displayAddress = Globals.Factory.CreateAction("To be replaced"); 

    // For .NET Framework 3.5 projects, use the following code to create the action.
    // displayAddress = new Microsoft.Office.Tools.Word.Action("To be replaced");

    // Add the action to the smart tag.
    smartTagDemo.Actions = new Microsoft.Office.Tools.Word.Action[] { 
        displayAddress };

    // Add the smart tag.
    this.VstoSmartTags.Add(smartTagDemo);

    displayAddress.BeforeCaptionShow += new
        Microsoft.Office.Tools.Word.BeforeCaptionShowEventHandler(
        displayAddress_BeforeCaptionShow);

    displayAddress.Click += new
        Microsoft.Office.Tools.Word.ActionClickEventHandler(
        displayAddress_Click);
}

void displayAddress_BeforeCaptionShow(object sender,
    Microsoft.Office.Tools.Word.ActionEventArgs e)
{
    Microsoft.Office.Tools.Word.Action clickedAction =
        sender as Microsoft.Office.Tools.Word.Action;

    if (clickedAction != null)
    {
        clickedAction.Caption = "Display the location of " +
            e.Text;
    }
}

void displayAddress_Click(object sender,
    Microsoft.Office.Tools.Word.ActionEventArgs e)
{
    int termStart = e.Range.Start;
    int termEnd = e.Range.End;
    System.Windows.Forms.MessageBox.Show("The recognized text '" + e.Text +
        "' begins at position " + termStart.ToString() +
        " and ends at position " + termEnd.ToString());
}

Seguridad

Debe habilitar las etiquetas inteligentes en Word. No están habilitadas de manera predeterminada. Para obtener más información, vea Cómo: Habilitar las etiquetas inteligentes en Word y en Excel.

Vea también

Tareas

Cómo: Habilitar las etiquetas inteligentes en Word y en Excel

Cómo: Agregar etiquetas inteligentes a libros de Excel

Cómo: Crear etiquetas inteligentes con reconocedores personalizados en Word y .NET Framework 3.5

Cómo: Crear etiquetas inteligentes con reconocedores personalizados en Excel y .NET Framework 3.5

Tutorial: Crear una etiqueta inteligente usando una personalización de nivel de documento.

Tutorial: Crear una etiqueta inteligente usando un complemento de nivel de aplicación

Conceptos

Arquitectura de las etiquetas inteligentes

Otros recursos

Información general sobre etiquetas inteligentes

Desarrollar soluciones de Office