menuStrip1动态添加菜单及快捷键
2024-10-18 12:25:39
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);
最新文章
- MATLAB中取整函数(fix, floor, ceil, round)的使用
- ubifs总体设计分析
- 从c开始,小小感悟
- JS中 escape, encodeURI 和 encodeURIComponent的区别
- 【LeetCode OJ】Binary Tree Maximum Path Sum
- angular todo
- BestCoder Round #3
- 关于硬盘和几种RAID
- 关于input标签无法对齐的解决方法!
- 添加本地jar包到本地的Maven仓库以及在Maven仓库中搜索想要添加的jar包
- Java线程安全性中的对象发布和逸出
- Django中多表查询思路
- spring初始化bean时执行某些方法完成特定的初始化操作
- Confluence 6 附件存储提取文本文件
- G - Throw nails
- 595. Big Countries --- SQL related from leetcode
- UT源码105032014098
- java入门--4110:圣诞老人的礼物-Santa Clau’s Gifts
- IIS错误提示:另一个程序正在使用此文件 进程无法访问
- linux 查看系统编码和修改系统 编码方法