如何响应ContextMenuStrip项目单击

时间:2011-04-26 10:31:11

标签: c# windows events contextmenu

目前我有以下代码:

ContextMenuStrip contexMenuuu = new ContextMenuStrip();

contexMenuuu.Items.Add("Edit ");
contexMenuuu.Items.Add("Delete " );
contexMenuuu.Show();

如何在点击某个项目时添加要处理的事件?

2 个答案:

答案 0 :(得分:33)

可以使用以下代码完成:

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
}

或者:

// ...

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
}

答案 1 :(得分:5)

Add方法返回ToolStripItem。因此,您可以为Click事件添加句柄

        var item = contexMenuuu.Items.Add("Edit ");
        item.Click += methodToBeInvoked;