Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# VSTO:使用变量访问CommandBarButton会产生无效引用-HRESULT异常:0x800A01A8_C#_Ms Word_Vsto - Fatal编程技术网

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

C# VSTO:使用变量访问CommandBarButton会产生无效引用-HRESULT异常:0x800A01A8,c#,ms-word,vsto,C#,Ms Word,Vsto,我试图在Word的命令栏中添加一个自定义按钮,然后将其更改为可见或不可见。正如我所看到的,我确保将按钮存储在一个类变量中,这样我的项就不会在垃圾收集时被取消分配。我知道稍后访问该项目的正确方法,如上面的教程所述,但我在右键单击处理程序中尝试以下方法有什么问题: public partial class ThisAddIn { private Office.CommandBar textContextMenu; private Office.CommandBarButton exa

我试图在Word的命令栏中添加一个自定义按钮,然后将其更改为可见或不可见。正如我所看到的,我确保将按钮存储在一个类变量中,这样我的项就不会在垃圾收集时被取消分配。我知道稍后访问该项目的正确方法,如上面的教程所述,但我在右键单击处理程序中尝试以下方法有什么问题:

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对象,但我缺少什么?以这种方式添加变量后,为什么不能从变量访问按钮


感谢您的反馈。

命令栏已被弃用,您需要改用Fluent UI控件。您在电脑上安装了什么Word版本


有关更多信息,请参阅

我用的是VS2013和2013这个词。命令栏的功能必须仍然存在;使用
CommandBarButton.FindControl
然后设置属性,就像上面的代码一样,对我来说很好。