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

时间:2014-12-02 21:13:07

标签: c# ms-word vsto

我正在尝试向Word的CommandBar之一添加自定义按钮,然后将其更改为可见或不可见。正如我在some tutorials中所述,我确保将按钮存储在类变量中,这样我的项目就不会在垃圾回收时解除分配。我知道以后访问该项目的正确方法,如上面的教程中所述,但我在右键单击处理程序中尝试下面的方式有什么问题:

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;
    }
}

我已经查找了VBA异常0x800A01A8 - 据我所知,我并没有尝试访问不存在的COM对象,但我错过了什么?为什么在以这种方式添加按钮后无法从变量中访问该按钮?

感谢您的反馈。

1 个答案:

答案 0 :(得分:0)

不推荐使用命令栏,您需要使用Fluent UI控件。您在PC上安装了哪个Word版本?

有关详细信息,请参阅Customizing Context Menus in Office 2010

相关问题