简体   繁体   English

VSTO:使用变量访问CommandBarButton会产生无效引用-HRESULT的异常:0x800A01A8

[英]VSTO: accessing CommandBarButton with variable yields invalid reference - Exception from HRESULT: 0x800A01A8

I am trying to add a custom button to one of Word's CommandBar 's, and then later change them to be visible or invisible. 我试图将自定义按钮添加到Word的CommandBar之一,然后在以后将它们更改为可见或不可见。 As prescribed in some tutorials that I have seen, I make sure to store the button in a class variable so my item isn't de-allocated upon garbage collection. 如我所见的一些教程中所述 ,请确保将按钮存储在类变量中,以便在垃圾回收时不会取消分配我的项目。 I know the correct way to access the item later, as stated in the tutorial above, but what is wrong with the way I try below in the right click handler: 我知道稍后访问该项目的正确方法,如上面的教程所述,但是我在右键单击处理程序中尝试下面的方法有什么问题:

public partial class ThisAddIn
{
    private Office.CommandBar textContextMenu;
    private Office.CommandBarButton exampleMenuItem;

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        // keep track of the menu for later
        textContextMenu = this.Application.CommandBars["Text"];
        // add a right click handler
        this.Application.WindowBeforeRightClick += new Word.ApplicationEvents4_WindowBeforeRightClickEventHandler(application_WindowBeforeRightClick);

        AddToToolbar();
    }

    private void AddToToolbar()
    {
        // Add a button to the command bar
        exampleMenuItem = (Office.CommandBarButton)textContextMenu.Controls.Add(
            Office.MsoControlType.msoControlButton,
            missing,
            missing,
            1,
            true);

        exampleMenuItem.Caption = "Test Button";
        exampleMenuItem.Tag = "testButton";
    }

    public void application_WindowBeforeRightClick(Word.Selection selection, ref bool Cancel)
    {
        // attempting to access the variable here throws the COM exception
        exampleMenuItem.Visible = false;
        // ... but, as in the tutorial, I can access the button like this:
        var exampleButton = (Office.CommandBarButton)textContextMenu.FindControl(
            buttonType, 
            missing, 
            "testButton");
        exampleButton.Visible = false;
    }
}

I've looked up the VBA exception 0x800A01A8 - as far as I know, I'm not trying to access a COM object that doesn't exist, but what am I missing? 我查找了VBA异常0x800A01A8-据我所知,我不是在尝试访问不存在的COM对象,但是我想念的是什么? Why can't I access the button from a variable after it has been added in this way? 以这种方式添加变量后,为什么不能从变量访问按钮?

Thanks for any feedback. 感谢您的任何反馈。

Command bars were deprecated, you need to use the Fluent UI controls instead. 不建议使用命令栏,而需要使用Fluent UI控件。 What Word version do you have installed on the PC? 您在PC上安装了哪个Word版本?

See Customizing Context Menus in Office 2010 for more information. 有关详细信息,请参阅Office 2010中的自定义上下文菜单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM