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>
///
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) + "]");
}