How to get the application instance * actual * host?

I have this code in a C # add-in for VBE (highlighting "VBE": not an MS-Office add-in):

public abstract class HostApplicationBase<TApplication> : IHostApplication
    where TApplication : class
{
    protected readonly TApplication Application;
    protected HostApplicationBase(string applicationName)
    {
        Application = (TApplication)Marshal.GetActiveObject(applicationName + ".Application");
    }

Where TApplication- interop class ApplicationMS-Office, for example, type Microsoft.Office.Interop.Excel.Application; here the parameter applicationNamewill be "Excel" for Excel.

The problem is that Marshal.GetActiveObjectonly the first created instance seems to return, and this is not necessarily the instance that hosts the current VBE environment, and this causes problems .

How can I get a real host application instance?

+4
source share
1 answer

, VBE:

  • CommandBarButton, . , .

  • . VBA, BuiltIn.

  • Application.Name .

VBE, . , , - "Microsoft Excel", - ( ThisWorkbook), .

            var appProperty = vbe.VBProjects
                .Cast<VBProject>()
                .Where(project => project.Protection == vbext_ProjectProtection.vbext_pp_none)
                .SelectMany(project => project.VBComponents.Cast<VBComponent>())
                .Where(component => component.Type == vbext_ComponentType.vbext_ct_Document
                && component.Properties.Count > 1)
                .SelectMany(component => component.Properties.OfType<Property>())
                .FirstOrDefault(property => property.Name == "Application");
            if (appProperty != null)
            {
                Application = (TApplication)appProperty.Object;
            }
            else
            {
                Application = (TApplication)Marshal.GetActiveObject(applicationName + ".Application");
            }

vbProjects , GetActiveObject.

0

Source: https://habr.com/ru/post/1610302/


All Articles