Share via


以程式設計方式在隱藏模式中使用 Word 對話方塊

您可以使用一個方法呼叫來執行複雜的作業,方法是叫用 Microsoft Office Word 中的內建對話框,而不向使用者顯示它們。 您可以使用 物件的 方法Dialog,而不呼叫 方法來執行DisplayExecute動作。

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

範例

下列程式代碼範例示範如何使用 隱藏模式中的 [頁面設定 ] 對話框來設定沒有使用者輸入的多個頁面設定屬性。 這些範例會使用 Dialog 對象來設定自定義頁面大小。 頁面設定的特定設定,例如上邊界、下邊界等等,都可以作為物件的晚期綁定屬性 Dialog 使用。 這些屬性會在運行時間由 Word 動態建立。

下列範例示範如何在 Visual Basic 專案中執行此工作,其中 Option Strict 已關閉,以及以 .NET Framework 4 為目標的 Visual C# 專案中。 在這些專案中,您可以在 Visual Basic 和 Visual C# 編譯程式中使用晚期綁定功能。 若要使用此範例,請從專案中的 ThisDocumentThisAddIn 類別執行它。

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

下列範例示範如何在 Option Strict 所在的 Visual Basic 專案中執行這項工作。 在這些專案中,您必須使用反映來存取晚期綁定屬性。 若要使用此範例,請從專案中的 ThisDocumentThisAddIn 類別執行它。

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