为 Microsoft Word 创建自动化客户端
- 启动 Visual Studio .NET。
- 在文件菜单上,单击新建,然后单击项目。从 Visual C# 项目类型中选择 Windows 应用程序。默认情况下会创建 Form1。
- 添加对 Microsoft Word 对象库的引用。为此,请按照下列步骤操作:
- 在项目菜单上,单击添加引用。
- 在 COM 选项卡上,找到 Microsoft Word 对象库,然后单击选择。
注意:Microsoft Office 2003 包含主 Interop 程序集 (PIA)。 Microsoft Office XP 不包含 PIA,但您可以下载 PIA。 有关 Office XP PIA 的其他信息,请单击下面的文章编号,以查看 Microsoft 知识库中相应的文章:328912 INFO:Microsoft Office XP PIA 可供下载 - 在添加引用对话框中单击确定以接受您的选择。如果系统提示您为选定的库生成包装,请单击是。
- 在视图菜单上,选择工具箱以显示工具箱,然后向 Form1 添加一个按钮。
- 双击 Button1。出现该窗体的代码窗口。
- 在代码窗口中,将以下代码
private void button1_Click(object sender, System.EventArgs e) { }
private void button1_Click(object sender, System.EventArgs e) {Word.Application oWord;Word._Document oDoc;object oMissing = Missing.Value;object oDocBuiltInProps;object oDocCustomProps;//Create an instance of Microsoft Word and make it visible.oWord = new Word.Application();oWord.Visible = true;//Create a new Document and get the BuiltInDocumentProperties collection.oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);oDocBuiltInProps = oDoc.BuiltInDocumentProperties;Type typeDocBuiltInProps = oDocBuiltInProps.GetType();//Get the Author property and display it.string strIndex = "Author";string strValue;object oDocAuthorProp = typeDocBuiltInProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty, null,oDocBuiltInProps, new object[] {strIndex} );Type typeDocAuthorProp = oDocAuthorProp.GetType();strValue = typeDocAuthorProp.InvokeMember("Value", BindingFlags.Default |BindingFlags.GetProperty,null,oDocAuthorProp,new object[] {} ).ToString();MessageBox.Show( "The Author is: " + strValue,"Author" );//Set the Subject property.strIndex = "Subject";strValue = "The Subject";typeDocAuthorProp.InvokeMember("Item", BindingFlags.Default | BindingFlags.SetProperty, null,oDocBuiltInProps, new object[] {strIndex,strValue} );//Add a property/value pair to the CustomDocumentProperties collection.oDocCustomProps = oDoc.CustomDocumentProperties;Type typeDocCustomProps = oDocCustomProps.GetType();strIndex = "Knowledge Base Article";strValue = "Q303296";object[] oArgs = {strIndex,false,MsoDocProperties.msoPropertyTypeString,strValue};typeDocCustomProps.InvokeMember("Add",BindingFlags.Default | BindingFlags.InvokeMethod, null, oDocCustomProps, oArgs );MessageBox.Show("Select \"Properties\" from the File menu "+ "to view the changes.\nSelect the Summary tab to view "+ "the Subject property and the Custom tab to view the Knowledge" + "Base Article property.", "Check File Properties",MessageBoxButtons.OK,MessageBoxIcon.Information); }
- 滚动到代码窗口顶部,然后将以下行添加到 using 指令列表的末尾:
using Microsoft.Office.Core; using Word = Microsoft.Office.Interop.Word; using System.Reflection;
- 按 F5 键运行该应用程序。
注意:DocumentProperties 和 DocumentProperty 接口是晚期绑定接口。若要使用这些接口,必须像对待 IDispatch 接口那样对待它们。