我们如何从Microsoft Office加载项调用Invoke(Delegate)方法?

问题描述 投票:0回答:1

问题:如何在Invoke(...)项目中使用Microsoft Office 2010-2016 VSTO方法。或者,VSTO项目是否有其他替代方案?

背景:我正在尝试将第三方Windows Forms应用程序的源代码实现到我的Microsoft Office VSTO add-in项目中。第三方供应商已为其用户提供了一个示例/示例作为带有源代码的Windows Form项目,并已要求其用户将该代码模仿到其其他项目(WPF,Office解决方案等)。

我已经能够实现其Windows Forms示例应用程序的所有部分,但我的VS2019项目中的VSTO无法识别以下代码行:

    Invoke(new IsActivatedDelegate(CheckIfActivated));

备注delegate void IsActivatedDelegate();是在其示例的Form1.cs文件中声明的委托,而CheckIfActivated()是在同一Form1.cs文件中声明的方法。

现在,我们知道Invoke(...)方法来自System.Windows.Forms命名空间的Control类。因此,不能在VSTO项目中使用。但是VSTO项目可能有其他选择。

UPDATE

以下摘自第三方示例代码的Form1.cs文件,该示例正在调用Invoke(...)方法:

...........
...........
void mnuActDeact_Click(object sender, EventArgs e)
{
    if (isGenuine)
    {
        // deactivate product without deleting the product key allows the user to easily reactivate
        try
        {
            ta.Deactivate(false);
        }
        catch (ThirdPartyObjectException ex)
        {
            MessageBox.Show("Failed to deactivate: " + ex.Message);
            return;
        }

        isGenuine = false;
        ShowTrial(true);
    }
    else
    {
        // Note: you can launch the ThirdPartyObject wizard or you can create you own interface

        // launch ThirdPartyObject.exe to get the product key from the user, and activate.
        Process TAProcess = new Process
        {
            StartInfo =
            {
                FileName = Path.Combine(
                    Path.GetDirectoryName(Application.ExecutablePath),"ThirdPartyObject.exe")
            },
            EnableRaisingEvents = true
        };

        TAProcess.Exited += p_Exited;
        TAProcess.Start();
    }
}

void p_Exited(object sender, EventArgs e)
{
    // remove the event
    ((Process) sender).Exited -= p_Exited;

    // the UI thread is running asynchronous to ThirdPartyObject closing that's why we can't call CheckIfActivated(); directly
    Invoke(new IsActivatedDelegate(CheckIfActivated));
}

delegate void IsActivatedDelegate();

void CheckIfActivated()
{
    bool isNowActivated = false;

    try
    {
        isNowActivated = ta.IsActivated();
    }
    catch (ThirdPartyObjectException ex)
    {
        MessageBox.Show("Failed to check if activated: " + ex.Message);
        return;
    }

    // recheck if activated
    if (isNowActivated)
    {
        isGenuine = true;
        ReEnableAppFeatures();
        ShowTrial(false);
    }
}
............
........
c# delegates vsto office-interop invoke
1个回答
0
投票

我希望您出于上下文的考虑而显示了代码...至少有几行...我知道这一点。如果你说

YourDelegate yd = new YourDelegate(YourMethod);

您可以替代:

yd.Invoke(new IsActivatedDelegate(CheckIfActivated));

with

yd(new IsActivatedDelegate(CheckIfActivated));
© www.soinside.com 2019 - 2024. All rights reserved.