我想获得单击的MenuStrip
项目的名称,以根据名称启动其他表单。
到目前为止,我已经尝试过了,但不起作用:
private void menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ToolStripMenuItem mi = sender as ToolStripMenuItem;
ToolStripItem menuItem = sender as ToolStripItem;
if(menuItem!= null)
{
ContextMenuStrip owner = menuItem.Owner as ContextMenuStrip;
if(owner!= null)
{
Control sourceControl = owner.SourceControl;
}
}
}
mi和menuItem都为null。有人能给我解释一下如何得到那件商品的名字吗?
您正在单击菜单条本身。双击菜单上的项目或生成这样的事件。
private void menu_ItemClicked(object sender, EventArgs e)
{
var itemText = (sender as ToolStripMenuItem).Text;
MessageBox.Show(itemText);
}
这对我有效:
private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
MessageBox.Show(e.ClickedItem.Text);
}
这里有另一种方法:
private void contextMenuStrip_Click(object sender, Eventargs e)
{
((System.Windows.Forms.ContextMenuStrip)(sender)).GetItemAt(((System.Windows.Forms.MouseEventArgs)(e)).X, ((System.Windows.Forms.MouseEventArgs)(e)).Y).Text
}
要在菜单条带上获取所选菜单项,可以执行以下操作:
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
string itemText = e.ClickedItem.Text;
switch (itemText)
{
case "menu name 1":
//do stuff
break;
case "menu name 2":
// do stuff
break;
}
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
string itemText = e.ClickedItem.Text;
switch (itemText)
{
case "menu name 1":
//do stuff
break;
case "menu name 2":
// do stuff
break;
}
}