笑话大全网 - 爆笑笑话 - C# winform 用contextmenustrip 动态生成菜单

C# winform 用contextmenustrip 动态生成菜单

示例代码:

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>

/// 添加子菜单

/// </summary>

/// <param name="text">要显示的文字,如果为 - 则显示为分割线</param>

/// <param name="cms">要添加到的子菜单集合</param>

/// <param name="callback">点击时触发的事件</param>

/// <returns>生成的子菜单,如果为分隔条则返回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) + "]");

}