C# winform 用contextmenustrip 动态生成菜单

2020-04-17 游戏 232阅读
示例代码:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//添加菜单一
ToolStripMenuItem subItem;
subItem = AddContextMenu("新闻", contextMenuStrip1.Items, null);
//添加子菜单
AddContextMenu("今日要闻", subItem.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("今日关注", subItem.DropDownItems, new EventHandler(MenuClicked));
//添加菜单二
subItem = AddContextMenu("笑话", contextMenuStrip1.Items, null);
//添加子菜单
AddContextMenu("现代笑话", subItem.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("古代笑话", subItem.DropDownItems, new EventHandler(MenuClicked));
}
///
/// 添加子菜单
/// </summary>
/// 要显示的文字,如果为 - 则显示为分割线</param>
/// 要添加到的子菜单集合</param>
/// 点击时触发的事件</param>
/// 生成的子菜单,如果为分隔条则返回null</returns>
ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback)
{
if (text == "-")
{
ToolStripSeparator tsp = new ToolStripSeparator();
cms.Add(tsp);
return null;
}
else if (!string.IsNullOrEmpty(text))
{
ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
if (callback != null) tsmi.Click += callback;
cms.Add(tsmi);
return tsmi;
}
return null;
}
void MenuClicked(object sender, EventArgs e)
{
MessageBox.Show("You Clicked Menu Item [" + ((sender as ToolStripMenuItem).Text) + "]");
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com