public partial class FormMkTest : Form
{
public FormMkTest()
{
InitializeComponent();
}
private void FormMkTest_Load(object sender, EventArgs e)
{
//添加菜单一文本中加入 &F 即ALT+F 打开某子菜单
ToolStripMenuItem subItem;
subItem = AddContextMenu("文件(&F)", menuStrip1.Items, null);
//添加子菜单
AddContextMenu("打开(&O)", subItem.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("下载(&D)", subItem.DropDownItems, new EventHandler(MenuClicked));
//添加菜单二
subItem = AddContextMenu("&Edit", menuStrip1.Items, null);
//添加子菜单
ToolStripMenuItem Grandson = AddContextMenu("&Update", subItem.DropDownItems, new EventHandler(MenuClicked));
//孙子
AddContextMenu("孙子级", Grandson.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("-", subItem.DropDownItems, null);//增加一个分割线
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);
tsmi.Tag = text + "TAG";
if (callback != null) tsmi.Click += callback;
cms.Add(tsmi);
return tsmi;
}
return null;
}
void MenuClicked(object sender, EventArgs e)
{
//以下主要是动态生成事件并打开窗体
//((sender as ToolStripMenuItem).Tag)强制转换
//ObjectHandle t = Activator.CreateInstance("WinForms", "WinForms.Form2");
//Form f = (Form)t.Unwrap();
//f.ShowDialog();
string s = (sender as ToolStripMenuItem).Text;
MessageBox.Show(s);
}
}
string mStr = "武藤兰(&F)";
string mStred = Regex.Replace(mStr, "\\(&.?\\)", "");
Console.Write(mStred);