以编程方式在隐藏模式下使用 Word 对话框
可以通过调用 Microsoft 办公室 Word 中的内置对话框而不向用户显示内置对话框来执行一个方法调用的复杂操作。 可以使用 Execute 对象的方法 Dialog 执行此操作,而无需调用 Display 该方法。
适用于: 本主题中的信息适用于 Word 的文档级项目和 VSTO 外接程序项目。 有关详细信息,请参阅办公室应用程序和项目类型提供的功能。
示例
下面的代码示例演示如何在隐藏模式下使用 “页面设置 ”对话框来设置没有用户输入的多个页面设置属性。 这些示例使用 Dialog 对象来配置自定义页面大小。 页面设置的特定设置(如上边距、下边距等)可用作对象的后期绑定属性 Dialog 。 这些属性在运行时由 Word 动态创建。
以下示例演示如何在 Visual Basic 项目中执行此任务,其中 Option Strict 处于关闭状态,在面向 .NET Framework 4 的 Visual C# 项目中。 在这些项目中,可以在 Visual Basic 和 Visual C# 编译器中使用后期绑定功能。 若要使用此示例,请从项目中的 ThisDocument
或 ThisAddIn
类运行它。
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();
以下示例演示如何在 Visual Basic 项目中执行此任务,其中选项严格处于打开位置。 在这些项目中,必须使用反射来访问后期绑定属性。 若要使用此示例,请从项目中的 ThisDocument
或 ThisAddIn
类运行它。
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