Cómo: Utilizar cuadros de diálogo de Word en modo oculto

Puede realizar operaciones complejas con una llamada al método invocando los cuadros de diálogo integrados en Microsoft Office Word sin mostrarlos al usuario. Puede hacerlo utilizando el método Execute del objeto Dialog sin llamar al método Display.

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 y Word 2010. Para obtener más información, vea Características disponibles por aplicación y tipo de proyecto de Office.

Ejemplos

En los siguientes ejemplos de código se muestra cómo usar el cuadro de diálogo Configurar página en modo oculto para establecer varias propiedades de configuración de página sin datos proporcionados por el usuario. En los ejemplos se usa un objeto Dialog para configurar un tamaño de página personalizado. Los valores específicos de la configuración de página, como el margen superior, el margen inferior, etc., están disponibles como propiedades del objeto Dialog enlazadas en tiempo de ejecución. Word crea estas propiedades dinámicamente, en tiempo de ejecución.

En el siguiente ejemplo se muestra cómo realizar esta tarea en proyectos de Visual Basic donde Option Strict está desactivada y en los proyectos de Visual C# destinados a .NET Framework 4. En estos proyectos, puede usar las características de enlace en tiempo de ejecución en los compiladores de Visual C# y Visual Basic. Para usar este ejemplo, ejecútelo desde la clase ThisDocument o ThisAddIn del proyecto.

Dim dialog As Word.Dialog = Application.Dialogs.Item(Word.WdWordDialog.wdDialogFilePageSetup)

' Set the properties of the dialog box.
' ControlChars.Quote() is used to represent the symbol for inches.
With dialog
    .PageWidth = 3.3 & ControlChars.Quote
    .PageHeight = 6 & ControlChars.Quote
    .TopMargin = 0.71 & ControlChars.Quote
    .BottomMargin = 0.81 & ControlChars.Quote
    .LeftMargin = 0.66 & ControlChars.Quote
    .RightMargin = 0.66 & ControlChars.Quote
    .HeaderDistance = 0.28 & ControlChars.Quote
    .Orientation = Word.WdOrientation.wdOrientPortrait
    .DifferentFirstPage = False
    .FirstPage = 0
    .OtherPages = 0

    ' Apply these settings only to the current selection with this line of code:
    .ApplyPropsTo = 3

    ' Apply the settings.
    .Execute()
End With
dynamic dialog = Application.Dialogs[Word.WdWordDialog.wdDialogFilePageSetup];
dialog.PageWidth = "3.3\"";
dialog.PageHeight = "6\"";
dialog.TopMargin = "0.71\"";
dialog.BottomMargin = "0.81\"";
dialog.LeftMargin = "0.66\"";
dialog.RightMargin = "0.66\"";
dialog.HeaderDistance = "0.28\"";
dialog.Orientation = "0";
dialog.DifferentFirstPage = "0";
dialog.FirstPage = "0";
dialog.OtherPages = "0";

// Apply these settings only to the current selection with this line of code:
dialog.ApplyPropsTo = "3";

// Apply the settings.
dialog.Execute(); 

En el siguiente ejemplo se muestra cómo realizar esta tarea en proyectos de Visual Basic donde Option Strict está activada y en los proyectos de Visual C# destinados a .NET Framework 3.5. En estos proyectos, debe usar la reflexión para tener acceso a las propiedades enlazadas en tiempo de ejecución. Para usar este ejemplo, ejecútelo desde la clase ThisDocument o ThisAddIn del proyecto.

Friend Sub PageSetupDialogHidden()
    Dim dialog As Word.Dialog = Application.Dialogs.Item(Word.WdWordDialog.wdDialogFilePageSetup)

    ' Set the properties of the dialog box.
    ' ControlChars.Quote() is used to represent the symbol for inches.
    InvokeHelper(dialog, "PageWidth", "3.3" & ControlChars.Quote)
    InvokeHelper(dialog, "PageHeight", "6" & ControlChars.Quote)
    InvokeHelper(dialog, "TopMargin", "0.71" & ControlChars.Quote)
    InvokeHelper(dialog, "BottomMargin", "0.81" & ControlChars.Quote)
    InvokeHelper(dialog, "LeftMargin", "0.66" & ControlChars.Quote)
    InvokeHelper(dialog, "RightMargin", "0.66" & ControlChars.Quote)
    InvokeHelper(dialog, "HeaderDistance", "0.28" & ControlChars.Quote)
    InvokeHelper(dialog, "Orientation", "0")
    InvokeHelper(dialog, "DifferentFirstPage", "0")
    InvokeHelper(dialog, "FirstPage", "0")
    InvokeHelper(dialog, "OtherPages", "0")

    ' Apply these settings only to the current selection with this line of code:
    InvokeHelper(dialog, "ApplyPropsTo", "3")

    ' Apply the settings.
    dialog.Execute()
End Sub

Private Shared Sub InvokeHelper(ByVal dialog As Word.Dialog, ByVal member As String, ByVal value As String)
    Dim dialogType As System.Type = GetType(Word.Dialog)

    ' Set the appropriate property of the dialog box.
    dialogType.InvokeMember(member,
        System.Reflection.BindingFlags.SetProperty Or
            System.Reflection.BindingFlags.Public Or
            System.Reflection.BindingFlags.Instance,
        Nothing, dialog, New Object() {value},
        System.Globalization.CultureInfo.InvariantCulture)
End Sub
private void PageSetupDialogHidden() 
{ 
    Word.Dialog dialog = Application.Dialogs[Word.WdWordDialog.wdDialogFilePageSetup];

    InvokeHelper(dialog, "PageWidth", "3.3\"");
    InvokeHelper(dialog, "PageHeight", "6\"");
    InvokeHelper(dialog, "TopMargin", "0.71\"");
    InvokeHelper(dialog, "BottomMargin", "0.81\"");
    InvokeHelper(dialog, "LeftMargin", "0.66\"");
    InvokeHelper(dialog, "RightMargin", "0.66\"");
    InvokeHelper(dialog, "HeaderDistance", "0.28\"");
    InvokeHelper(dialog, "Orientation", "0");
    InvokeHelper(dialog, "DifferentFirstPage", "0");
    InvokeHelper(dialog, "FirstPage", "0");
    InvokeHelper(dialog, "OtherPages", "0");

    // Apply these settings only to the current selection with this line of code:
    InvokeHelper(dialog, "ApplyPropsTo", "3"); 

    // Apply the settings.
    dialog.Execute(); 
}

private static void InvokeHelper(Word.Dialog dialog, string member, string value)
{
    System.Type dialogType = typeof(Word.Dialog);

    // Set the appropriate property of the dialog box.
    dialogType.InvokeMember(member,
        System.Reflection.BindingFlags.SetProperty |
            System.Reflection.BindingFlags.Public |
            System.Reflection.BindingFlags.Instance,
        null, dialog, new object[] { value },
        System.Globalization.CultureInfo.InvariantCulture);
}

Vea también

Tareas

Cómo: Utilizar cuadros de diálogo integrados en Word

Enlace en tiempo de ejecución en las soluciones de Office

Referencia

Reflexión (C# y Visual Basic)

Otros recursos

Información general acerca del modelo de objetos de Word