使用VSTO禁用右键菜单按钮

using Excel = Microsoft.Office.Interop.Excel;

public void DisableRowColumnContextMenuButtons()
{
    Excel.Application app = Globals.ThisAddIn.Application;
    Excel.CommandBars contextMenuBars = app.CommandBars["Cell"];
    Excel.CommandBar contextMenuRow = contextMenuBars.Controls["Row"];
    Excel.CommandBar contextMenuColumn = contextMenuBars.Controls["Column"];

    // Disable specific buttons in the row context menu
    contextMenuRow.Controls["Cut"].Enabled = false;
    contextMenuRow.Controls["Copy"].Enabled = false;
    contextMenuRow.Controls["Insert"].Enabled = false;
    // Disable specific buttons in the column context menu
    contextMenuColumn.Controls["Cut"].Enabled = false;
    contextMenuColumn.Controls["Copy"].Enabled = false;
    contextMenuColumn.Controls["Insert"].Enabled = false;
}

I apologize for the confusion. It appears that the approach using `app.CommandBars["row"]` to add a right-click button may not be working as expected.

If you want to add a custom right-click button to the row context menu in Excel, you can try using the following code snippet:

```csharp
using Excel = Microsoft.Office.Interop.Excel;

public void AddRightClickButtonToRowContextMenu()
{
    Excel.Application app = Globals.ThisAddIn.Application;
    Excel.CommandBars contextMenuBars = app.CommandBars["Cell"];
    Excel.CommandBar contextMenu = contextMenuBars.Controls["Row"];

    // Add a button to the row context menu
    Excel.CommandBarButton button = (Excel.CommandBarButton)contextMenu.Controls.Add(
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    button.Caption = "My Row Button";
    button.Tag = "MyRowButtonTag";
    button.OnAction = app.GetCustomUI("MyRowMenuItem_Click").ToString();
}
```

Make sure to replace `"My Row Button"` with the desired caption for your button and `"MyRowButtonTag"` with the desired tag value. Also, update `"MyRowMenuItem_Click"` with the name of the method that should be called when the button is clicked.

Please note that the above code assumes you're using VSTO and have the necessary references imported. Additionally, this approach relies on the older CommandBars API, which may not work in newer versions of Excel or in certain scenarios.

It's recommended to use the modern Ribbon XML or Office JavaScript API for creating custom functionality in Excel, as mentioned in the previous responses. These methods provide better compatibility and flexibility across different Excel versions and platforms.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值