以编程方式在 Word 中使用内置对话框

使用 Microsoft 办公室 Word 时,有时需要显示用户输入的对话框。 虽然可以创建自己的对话框,但你可能还需要采用在 Word 中使用内置对话框的方法,该对话框在对象的集合ApplicationDialogs公开。 这样,便可以访问 200 多个内置对话框,这些对话框表示为枚举。

适用于: 本主题中的信息适用于 Word 的文档级项目和 VSTO 外接程序项目。 有关详细信息,请参阅办公室应用程序和项目类型提供的功能。

显示对话框

若要显示对话框,请使用枚举的值 WdWordDialog 之一创建表示 Dialog 要显示的对话框的对象。 然后,调用 Show 对象的方法 Dialog

下面的代码示例演示如何显示 “打开 文件”对话框。 若要使用此示例,请从项目中的 ThisDocumentThisAddIn 类运行它。

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

可通过后期绑定获取的访问对话框成员

Word 中某些对话框的属性和方法只能通过后期绑定使用。 在启用 Option StrictVisual Basic 项目中,必须使用反射来访问这些成员。 有关详细信息,请参阅办公室解决方案中的后期绑定。

下面的代码示例演示如何在 Visual Basic 项目中使用“文件打开”对话框的 Name 属性,其中 Option Strict 处于关闭状态,或在面向 .NET Framework 4 或 .NET Framework 4.5 的 Visual C# 项目中。 若要使用此示例,请从项目中的 ThisDocumentThisAddIn 类运行它。

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

下面的代码示例演示如何使用反射来访问 Visual Basic 项目中“选项严格”所在的 Visual Basic 对话框中的“文件打开”对话框的 Name 属性。 若要使用此示例,请从项目中的 ThisDocumentThisAddIn 类运行它。

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))