程序 VSTO 外接程序Program VSTO Add-ins

通过创建 VSTO 外接程序扩展 Microsoft Office 应用程序时,可以直接接针对项目中的 ThisAddIn 类编写代码。When you extend a Microsoft Office application by creating a VSTO Add-in, you write code directly against the ThisAddIn class in your project. 此类可用于执行下列任务,例如:访问 Microsoft Office 主机应用程序的对象模型、自定义应用程序的用户界面 (UI) 和向其他 Office 解决方公开 VSTO 外接程序中的对象。You can use this class to perform tasks such as accessing the object model of the Microsoft Office host application, customizing the user interface (UI) of the application, and exposing objects in your VSTO Add-in to other Office solutions.

适用于: 本主题中的信息适用于 VSTO 添加-在项目中。Applies to: The information in this topic applies to VSTO Add-in projects. 有关详细信息,请参阅按 Office 应用程序和项目类型提供的功能For more information, see Features available by Office application and project type.

在 VSTO 外接程序项目中编写代码与在 Visual Studio 中编写其他类型项目的代码在某些方面存在不同。Some aspects of writing code in VSTO Add-in projects are different from other types of projects in Visual Studio. 其中许多差异是由 Office 对象模型公开给托管代码的方式引起的。Many of these differences are caused by the way the Office object models are exposed to managed code. 有关详细信息,请参阅在 Office 解决方案中编写代码For more information, see Write code in Office solutions.

有关可以通过使用 Visual Studio 中的 Office 开发工具创建的 VSTO 外接程序和其他类型的解决方案的常规信息,请参阅office 解决方案开发(概述)VSTOFor general information about VSTO Add-ins and other types of solutions you can create by using the Office development tools in Visual Studio, see Office solutions development overview (VSTO).

使用 ThisAddIn 类Use the ThisAddIn class

你可以在 ThisAddIn 类中开始编写 VSTO 外接程序代码。You can start writing your VSTO Add-in code in the ThisAddIn class. Visual Studio 会自动在 VSTO 外接程序项目中的 ThisAddIn Visual BasicVisual Basic(在中)或C# ThisAddIn.cs (in)代码文件中生成此类。Visual Studio automatically generates this class in the ThisAddIn.vb (in Visual BasicVisual Basic) or ThisAddIn.cs (in C#) code file in your VSTO Add-in project. 当 Microsoft Office 应用程序加载 VSTO 外接程序时, Visual Studio Tools for Office RuntimeVisual Studio Tools for Office runtime 将为你自动实例化此类。The Visual Studio Tools for Office RuntimeVisual Studio Tools for Office runtime automatically instantiates this class for you when the Microsoft Office application loads your VSTO Add-in.

ThisAddIn 类中有两个默认的事件处理程序。There are two default event handlers in the ThisAddIn class. 若要在加载 VSTO 外接程序后运行代码,请将代码添加到 ThisAddIn_Startup 事件处理程序。To run code when the VSTO Add-in is loaded, add code to the ThisAddIn_Startup event handler. 若要在卸载 VSTO 外接程序前运行代码,请将代码添加到 ThisAddIn_Shutdown 事件处理程序。To run code just before the VSTO Add-in is unloaded, add code to the ThisAddIn_Shutdown event handler. 有关这些事件处理程序的详细信息,请参阅Office 项目中的事件For more information about these event handlers, see Events in Office projects.

Note

在 Outlook 中,卸载 VSTO 外接程序时默认情况下不会始终调用 ThisAddIn_Shutdown 事件处理程序。In Outlook, by default the ThisAddIn_Shutdown event handler is not always called when the VSTO Add-in is unloaded. 有关详细信息,请参阅Office 项目中的事件For more information, see Events in Office projects.

访问主机应用程序的对象模型Access the object model of the host application

若要访问主机应用程序的对象模型,请使用 Application 类的 ThisAddIn 字段。To access the object model of the host application, use the Application field of the ThisAddIn class. 此字段会返回一个表示主机程序当前实例的对象。This field returns an object that represents the current instance of the host application. 下表列出了每个 VSTO 外接程序项目中 Application 字段的返回值类型。The following table lists the type of the return value for the Application field in each VSTO Add-in project.

主机应用程序Host application 返回值类型Return value type
Microsoft Office ExcelMicrosoft Office Excel Application
Microsoft Office InfoPathMicrosoft Office InfoPath Application
Microsoft Office OutlookMicrosoft Office Outlook Application
Microsoft Office PowerPointMicrosoft Office PowerPoint 应用程序Application
Microsoft Office ProjectMicrosoft Office Project Microsoft.Office.Interop.MSProject.ApplicationMicrosoft.Office.Interop.MSProject.Application
Microsoft Office VisioMicrosoft Office Visio Microsoft.Office.Interop.Visio.ApplicationMicrosoft.Office.Interop.Visio.Application
Microsoft Office WordMicrosoft Office Word Application

下面的代码示例演示如何使用Application字段在 Microsoft Office Excel 的 VSTO 外接程序中创建新的工作簿。The following code example shows how to use the Application field to create a new workbook in a VSTO Add-in for Microsoft Office Excel. 此示例应从 ThisAddIn 类运行。This example is intended to be run from the ThisAddIn class.

Dim newWorkbook As Excel.Workbook = Me.Application.Workbooks.Add()
Excel.Workbook newWorkbook = this.Application.Workbooks.Add(System.Type.Missing);

若要从 ThisAddIn 类的外部执行相同操作,请使用 Globals 对象访问 ThisAddIn 类。To do the same thing from outside the ThisAddIn class, use the Globals object to access the ThisAddIn class. 有关Globals对象的详细信息,请参阅对 Office 项目中对象的全局访问For more information about the Globals object, see Global access to objects in Office projects.

Dim newWorkbook As Excel.Workbook = Globals.ThisAddIn.Application.Workbooks.Add()
Excel.Workbook newWorkbook = Globals.ThisAddIn.Application.Workbooks.Add(System.Type.Missing);

有关特定 Microsoft Office 应用程序的对象模型的详细信息,请参阅以下主题:For more information about the object models of specific Microsoft Office applications, see the following topics:

在 Office 应用程序启动时访问文档Access a document when the Office application starts

并非所有 Office 2010Office 2010 应用程序都会在启动时自动打开文档,任何 Office 2013Office 2013 应用程序在启动时都不会打开文档。Not all Office 2010Office 2010 applications automatically open a document when you start them, and none of the Office 2013Office 2013 applications open a document when you start them. 因此,如果代码要求打开文档ThisAdd-In_Startup ,请不要在事件处理程序中添加代码。Therefore, don't add code in the ThisAdd-In_Startup event handler if the code requires a document to be open. 相反,请将该代码添加到用户创建或打开文档时 Office 应用程序引发的事件。Instead, add that code to an event that the Office application raises when a user creates or opens a document. 这样,可以保证在代码执行对文档的操作前,该文档已打开。That way, you can guarantee that a document is open before your code performs operations on it.

仅当在用户创建一个文档或打开现有文档时,以下代码示例才会使用 Word 中的文档。The following code example works with a document in Word only when the user creates a document or opens an existing document.

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        this.Application.DocumentOpen +=
new Word.ApplicationEvents4_DocumentOpenEventHandler(WorkWithDocument);

        ((Word.ApplicationEvents4_Event)this.Application).NewDocument +=
            new Word.ApplicationEvents4_NewDocumentEventHandler(WorkWithDocument);  
    }
    
    private void WorkWithDocument(Microsoft.Office.Interop.Word.Document Doc)
    {
        try
        {
            Word.Range rng = Doc.Range(0, 0);
            rng.Text = "New Text";
            rng.Select();
        }
        catch (Exception ex)
        {
            // Handle exception if for some reason the document is not available.
        }
    }
Private Sub ThisAddIn_Startup() Handles Me.Startup

    AddHandler Application.NewDocument, AddressOf WorkWithDocument

End Sub

Private Sub WorkWithDocument(ByVal Doc As Microsoft.Office.Interop.Word.Document) _
    Handles Application.DocumentOpen

    Dim rng As Word.Range = Doc.Range(Start:=0, End:=0)
    rng.Text = " New Text "
    rng.Select()

End Sub

用于其他任务的 ThisAddIn 成员ThisAddIn members to use for other tasks

下表描述了其他常见任务,并显示了你可以用以执行这些任务的 ThisAddIn 类的成员类型。The following table describes other common tasks and shows which members of the ThisAddIn class you can use to perform the tasks.

任务Task 供使用的成员Member to use
运行代码以在加载 VSTO 外接程序时初始化 VSTO 外接程序。Run code to initialize the VSTO Add-in when the VSTO Add-in is loaded. 将代码添加到 ThisAddIn_Startup 方法。Add code to the ThisAddIn_Startup method. 这是 Startup 事件的默认事件处理程序。This is the default event handler for the Startup event. 有关详细信息,请参阅Office 项目中的事件For more information, see Events in Office projects.
运行代码以清理 VSTO 外接程序在被卸载前使用的资源。Run code to clean up resources used by the VSTO Add-in before the VSTO Add-in is unloaded. 将代码添加到 ThisAddIn_Shutdown 方法。Add code to the ThisAddIn_Shutdown method. 这是 Shutdown 事件的默认事件处理程序。This is the default event handler for the Shutdown event. 有关详细信息,请参阅Office 项目中的事件For more information, see Events in Office projects. 注意: 在 Outlook 中,卸载 VSTO 外接程序时默认情况下不会始终调用 ThisAddIn_Startup 事件处理程序。Note: In Outlook, by default the ThisAddIn_Startup event handler is not always called when the VSTO Add-in is unloaded. 有关详细信息,请参阅Office 项目中的事件For more information, see Events in Office projects.
显示自定义任务窗格。Display a custom task pane. 使用 CustomTaskPanes 字段。Use the CustomTaskPanes field. 有关详细信息,请参阅自定义任务窗格For more information, see Custom task panes.
向其他 Microsoft Office 解决方案公开 VSTO 外接程序中的对象。Expose objects in your VSTO Add-in to other Microsoft Office solutions. 重写 RequestComAddInAutomationService 方法。Override the RequestComAddInAutomationService method. 有关详细信息,请参阅从其他 Office 解决方案调用 VSTO 外接程序中的代码For more information, see Call code in VSTO Add-ins from other Office solutions.
通过实现可扩展性接口,在 Microsoft Office 系统中自定义功能。Customize a feature in the Microsoft Office system by implementing an extensibility interface. 重写 RequestService 方法以返回实现该接口的类的实例。Override the RequestService method to return an instance of a class that implements the interface. 有关详细信息,请参阅使用扩展性接口自定义 UI 功能For more information, see Customize UI features by using extensibility interfaces. 注意: 若要自定义功能区 UI,你可以重写 CreateRibbonExtensibilityObject 方法。Note: To customize the ribbon UI, you can also override the CreateRibbonExtensibilityObject method.

了解 ThisAddIn 类的设计Understand the design of the ThisAddIn class

在面向 .NET Framework 4.NET Framework 4的项目中, AddIn 是一个接口。In projects that target the .NET Framework 4.NET Framework 4, AddIn is an interface. ThisAddIn 类是从 AddInBase 类派生的。The ThisAddIn class derives from the AddInBase class. 此基类会将对其成员的所有调用都重定向到 AddInVisual Studio Tools for Office RuntimeVisual Studio Tools for Office runtime接口的内部实现。This base class redirects all calls to its members to an internal implementation of the AddIn interface in the Visual Studio Tools for Office RuntimeVisual Studio Tools for Office runtime.

在 Outlook 的 VSTO 外接程序项目中,ThisAddIn 类派生自面向 .NET Framework 3.5 的项目中的 Microsoft.Office.Tools.Outlook.OutlookAddIn 类,以及面向 .NET Framework 4.NET Framework 4 的项目中的 OutlookAddInBaseIn VSTO Add-in projects for Outlook, the ThisAddIn class derives from the Microsoft.Office.Tools.Outlook.OutlookAddIn class in projects that target the .NET Framework 3.5, and from OutlookAddInBase in projects that target the .NET Framework 4.NET Framework 4. 这些基类提供了一些附加功能以支持窗体区域。These base classes provide some additional functionality to support form regions. 有关窗体区域的详细信息,请参阅创建 Outlook 窗体区域For more information about form regions, see Create Outlook form regions.

自定义 Microsoft Office 应用程序的用户界面Customize the user interface of Microsoft Office applications

通过使用 VSTO 外接程序,你能以编程方式自定义 Microsoft Office 应用程序的 UI。You can programmatically customize the UI of Microsoft Office applications by using a VSTO Add-in. 例如,你可以在 Outlook 中自定义功能区、显示自定义任务窗格或创建自定义窗体区域。For example, you can customize the ribbon, display a custom task pane, or create a custom form region in Outlook. 有关详细信息,请参阅OFFICE UI 自定义For more information, see Office UI customization.

Visual Studio 提供了可用于创建自定义任务窗格、功能区自定义和 Outlook 窗体区域的设计器和类。Visual Studio provides designers and classes that you can use to create custom task panes, ribbon customizations, and Outlook form regions. 这些设计器和类有助于简化自定义这些功能的过程。These designers and classes help to simplify the process of customizing these features. 有关详细信息,请参阅自定义任务窗格功能区设计器创建 Outlook 窗体区域For more information, see Custom task panes, Ribbon Designer, and Create Outlook form regions.

如果你想要以类和设计器不支持的方式自定义这些功能之一,则还可以通过在 VSTO 外接程序中实现 扩展性接口 来自定义这些功能。If you want to customize one of these features in a way that is not supported by the classes and designers, you can also customize these features by implementing an extensibility interface in your VSTO Add-in. 有关详细信息,请参阅使用扩展性接口自定义 UI 功能For more information, see Customize UI features by using extensibility interfaces.

此外,你还可以通过生成扩展文档和工作簿的行为的主机项来修改 Word 文档和 Excel 工作簿的 UI。In addition, you can modify the UI of Word documents and Excel workbooks by generating host items that extend the behavior of documents and workbooks. 这样,你便可以将托管控件添加到文档和工作表。This enables you to add managed controls to documents and worksheets. 有关详细信息,请参阅在运行时在 VSTO 外接程序中扩展 Word 文档和 Excel 工作簿For more information, see Extend Word documents and Excel workbooks in VSTO Add-ins at run time.

从其他解决方案调用 VSTO 外接程序中的代码Call code in VSTO Add-ins from other solutions

你可以向其他解决方案(包括其他 Office 解决方案)公开 VSTO 外接程序中的对象。You can expose objects in your VSTO Add-in to other solutions, including other Office solutions. 如果 VSTO 外接程序提供了你希望使其他解决方案能够使用的服务,这一点非常有用。This is useful if your VSTO Add-in provides a service that you want to enable other solutions to use. 例如,如果您有 Microsoft Office Excel 的 VSTO 外接程序从 web 服务中执行财务数据计算,则其他解决方案可以通过在运行时调用 Excel VSTO 外接程序来执行这些计算。For example, if you have a VSTO Add-in for Microsoft Office Excel that performs calculations on financial data from a web service, other solutions can perform these calculations by calling into the Excel VSTO Add-in at run time.

有关详细信息,请参阅从其他 Office 解决方案调用 VSTO 外接程序中的代码For more information, see Call code in VSTO Add-ins from other Office solutions.

请参阅See also