Edit

Share via


Programmatically use built-in dialog boxes in Word

When working with Microsoft Office Word, there are times when you need to display dialog boxes for user input. Although you can create your own, you might also want to take the approach of using the built-in dialog boxes in Word, which are exposed in the Dialogs collection of the Application object. This enables you to access over 200 of the built-in dialog boxes, which are represented as enumerations.

Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Word. For more information, see Features available by Office application and project type.

Display dialog boxes

To display a dialog box, use one of the values of the WdWordDialog enumeration to create a Dialog object that represents the dialog box you want to display. Then, call the Show method of the Dialog object.

The following code example demonstrates how to display the File Open dialog box. To use this example, run it from the ThisDocument or ThisAddIn class in your project.

Word.Dialog dlg = Application.Dialogs[Word.WdWordDialog.wdDialogFileOpen];
dlg.Show();

Access dialog box members that are available through late binding

Some properties and methods of dialog boxes in Word are available only through late binding. In Visual Basic projects where Option Strict is on, you must use reflection to access these members. For more information, see Late binding in Office solutions.

The following code example demonstrates how to use the Name property of the File Open dialog box in Visual Basic projects where Option Strict is off or in Visual C# projects that target the .NET Framework 4 or the .NET Framework 4.5. To use this example, run it from the ThisDocument or ThisAddIn class in your project.

dynamic dialog = Application.Dialogs[Word.WdWordDialog.wdDialogFileOpen];
dialog.Name = "Testing";
dialog.Show();
MessageBox.Show(dialog.Name);

The following code example demonstrates how to use reflection to access the Name property of the File Open dialog box in Visual Basic projects where Option Strict is on. To use this example, run it from the ThisDocument or ThisAddIn class in your project.

Dim dlg As Word.Dialog = Application.Dialogs(Word.WdWordDialog.wdDialogFileOpen)
Dim dlgType As Type = GetType(Word.Dialog)

' Set the Name property of the dialog box.
dlgType.InvokeMember("Name", _
    Reflection.BindingFlags.SetProperty Or _
        Reflection.BindingFlags.Public Or _
        Reflection.BindingFlags.Instance, _
    Nothing, dlg, New Object() {"Testing"}, _
    System.Globalization.CultureInfo.InvariantCulture)

' Display the dialog box.
dlg.Show()

' Show the Name property.
MessageBox.Show(dlgType.InvokeMember("Name", _
    Reflection.BindingFlags.GetProperty Or _
        Reflection.BindingFlags.Public Or _
        Reflection.BindingFlags.Instance, _
    Nothing, dlg, Nothing, _
    System.Globalization.CultureInfo.InvariantCulture))