How to respond to a ContextMenuStrip item click

后端 未结 2 718
别那么骄傲
别那么骄傲 2021-01-07 17:45

Currently I have the following code:

ContextMenuStrip contexMenuuu = new ContextMenuStrip();

contexMenuuu.Items.Add(\"Edit \");
contexMenuuu.Items.Add(\"Del         


        
相关标签:
2条回答
  • 2021-01-07 18:08

    Add method returns ToolStripItem. So you can add handle to Click event

            var item = contexMenuuu.Items.Add("Edit ");
            item.Click += methodToBeInvoked;
    
    0 讨论(0)
  • 2021-01-07 18:17

    This can be done using the following code:

    ContextMenuStrip contexMenu = new ContextMenuStrip();
    
    contexMenu.Items.Add("Edit ");
    contexMenu.Items.Add("Delete ");
    contexMenu.Show();
    contexMenu.ItemClicked += new ToolStripItemClickedEventHandler(
        contexMenu_ItemClicked);
    
    // ...
    
    void contexMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) {
        ToolStripItem item = e.ClickedItem;
        // your code here
    }
    

    Or alternatively:

    // ...
    
    ToolStripItem item = contexMenu.Items.Add("Edit ");
    item.Click += new EventHandler(item_Click);
    
    // ...
    
    void item_Click(object sender, EventArgs e) {
        ToolStripItem clickedItem = sender as ToolStripItem;
        // your code here
    }
    
    0 讨论(0)
提交回复
热议问题