共用方式為


以程序設計方式在 Word 中使用內建對話方塊

使用 Microsoft Office Word 時,有時候您需要顯示使用者輸入的對話方塊。 雖然您可以自行建立,但您也可以使用 Word 中的內建對話框,在物件集合ApplicationDialogs公開的方法。 這可讓您存取超過 200 個內建對話框,這些對話框會以列舉表示。

適用於: 本主題中的資訊適用於 Word 的文件層級專案和 VSTO 載入宏專案。 如需詳細資訊,請參閱 Office 應用程式 lication 和項目類型所提供的功能。

顯示對話框

若要顯示對話框,請使用 列舉的 WdWordDialog 其中一個值來建立 Dialog 物件,代表您想要顯示的對話框。 然後,呼叫 Show 物件的方法 Dialog

下列程式代碼範例示範如何顯示 [ 開啟 檔案] 對話框。 若要使用此範例,請從專案中的 ThisDocumentThisAddIn 類別執行它。

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

可透過晚期系結取得的存取對話框成員

Word 中某些對話框的屬性和方法只能透過晚期系結來使用。 在選項 Strict 開啟的 Visual Basic 專案中,您必須使用反映來存取這些成員。 如需詳細資訊,請參閱 Office 解決方案中的晚期系結。

下列程式代碼範例示範如何在 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 專案中 Option Strict 所在的 [檔案開啟] 對話方塊的 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))