Dynamically Disable Particular Context Menu Item

2020-08-17 02:12发布

问题:

I've added 4 menus in context menu. If during the start context menu item is clicked, how to disable that particular ("Start") menu item?

ContextMenu conMenu1 = new ContextMenu();
public Form1()
{
            InitializeComponent();
    conMenu1.MenuItems.Add("Start", new System.EventHandler(this.Start_Click));
    conMenu1.MenuItems.Add("Pause", new System.EventHandler(this.Pause_Click));
    conMenu1.MenuItems.Add("Resume", new System.EventHandler(this.Resume_Click));
    conMenu1.MenuItems.Add("Stop", new System.EventHandler(this.Stop_Click));
}

private void Start_Click(object sender, EventArgs e)
{
    // Functionalities to disable start context menu item
}

回答1:

You can do like this. Handle the ContextMenu.Opening Event

private void conMenu1_Opening(object sender, CancelEventArgs e)
{
    conMenu1.Items[0].Enabled= false;
}


回答2:

Use PopUp event such as

Declaration

var trayMenu = new ContextMenu();
trayMenu.Popup += MenuOpening;

trayMenu.MenuItems.Add(...);
...

Subscribed Event

private void MenuOpening(object sender, EventArgs e)
{         
    var cm = sender as ContextMenu;

    if (cm != null)
         cm.MenuItems[0].Enabled = false;
}


标签: c# .net winforms