如何:以编程方式使用 Word 中的内置对话框

使用 Microsoft Office Word 时,有时需要显示用户输入对话框。虽然可以创建自己的对话框,您也许还希望采用使用 Word 中内置对话框的方法,这些对话框在 Application 对象的 Dialogs 集合中公开。这使您能够访问 200 个以上的内置对话框,它们以枚举的形式表示。

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

显示对话框

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

下面的代码示例演示如何显示**“打开”**对话框。若要使用此示例,请从项目内的 ThisDocument 或 ThisAddIn 类中运行此示例。

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

ahzbkf8e.collapse_all(zh-cn,VS.110).gif访问可通过后期绑定使用的对话框成员

Word 中对话框的某些属性和方法只能通过后期绑定使用。在 Visual Basic 项目 Option Strict 位置打开,您必须使用反射来访问这些成员。有关更多信息,请参见Office 解决方案中的后期绑定

下面的代码示例在 Option Strict 或在 Visual C# 项目面向 .NET Framework 4 或 .NET Framework 4.5的 Visual Basic 项目演示如何使用 文件已打开 对话框的 Name 属性。若要使用此示例,请从项目内的 ThisDocument 或 ThisAddIn 类中运行此示例。

Private Sub TestDynamicDialog()
    Dim dialog As Word.Dialog = Application.Dialogs(Word.WdWordDialog.wdDialogFileOpen)
    dialog.Name = "Testing"
    dialog.Show()
    MessageBox.Show(dialog.Name)
End Sub
dynamic dialog = Application.Dialogs[Word.WdWordDialog.wdDialogFileOpen];
dialog.Name = "Testing";
dialog.Show();
MessageBox.Show(dialog.Name);

下面的代码示例演示如何使用反射来 文件已打开 对话框 Name 属性在 Visual Basic 中的项目的访问 Option Strict 位置打开。若要使用此示例,请从项目内的 ThisDocument 或 ThisAddIn 类中运行此示例。

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

请参见

参考

Option Strict 语句

反射(C# 和 Visual Basic)

概念

如何:以编程方式在隐藏模式下使用 Word 对话框

Office 解决方案中的可选参数

其他资源

Word 对象模型概述