如何在c#中添加menuitem

时间:2015-06-19 15:26:18

标签: c#

我已尝试使用此代码在右键单击word文档中添加新菜单项。但是有一个问题

错误:' this.Application'此行给出的语句错误不在当前上下文中。这条线或任何其他解决方案需要什么样的解决方案。

Word.Application application;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    application = this.Application;
    application.WindowBeforeRightClick +=
        new Word.ApplicationEvents4_WindowBeforeRightClickEventHandler(application_WindowBeforeRightClick);

    application.CustomizationContext = application.ActiveDocument;

    Office.CommandBar commandBar = application.CommandBars["Text"];
    Office.CommandBarButton button = (Office.CommandBarButton)commandBar.Controls.Add(
        Office.MsoControlType.msoControlButton);
    button.accName = "My Custom Button";
    button.Caption = "My Custom Button";
}

public void application_WindowBeforeRightClick(Word.Selection selection, ref bool Cancel)
{
    if (selection != null && !String.IsNullOrEmpty(selection.Text))
    {
        string selectionText = selection.Text;

        if (selectionText.Contains("C#"))
            SetCommandVisibility("My Custom Button", false);
        else
            SetCommandVisibility("My Custom Button", true);
    }
}

private void SetCommandVisibility(string name, bool visible)
{
    application.CustomizationContext = application.ActiveDocument;
    Office.CommandBar commandBar = application.CommandBars["Text"];
    commandBar.Controls[name].Visible = visible;
}

0 个答案:

没有答案