【问题标题】:How to get click event handler names of ToolStripDropDownItem?如何获取 ToolStripDropDownItem 的单击事件处理程序名称?
【发布时间】:2022-11-19 21:29:11
【问题描述】:

我在Windows Forms 有一个旧项目,它有超过 300 个菜单,整个 MDI 窗体都有菜单点击事件。 有什么方法可以获取字符串中的点击事件名称(例如“toolStripMenuItem_Click”)? 我这样试过

foreach (ToolStripMenuItem menu in menuStrip.Items)
{
   foreach (ToolStripDropDownItem submenu in menu.DropDownItems)
   {
       var _events= submenu.GetType()
                     .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
                     .OrderBy(pi => pi.Name).ToList();
   }
}

但它总是返回空的。实现这一目标的正确方法是什么?

【问题讨论】:

  • 如果您在运行时需要名称:您的事件处理程序是否遵循名称以菜单项本身的名称开头的约定?
  • 为什么你想要这个信息吗?你想解决什么问题? (并反映类型ToolStripDropDownItem 不会告诉你任何关于你自己项目的内容)
  • @NineBerry 有些菜单有不同的处理程序。休息遵循惯例。
  • @Dai 我打算根据用户权限动态生成菜单。由于所有菜单点击处理程序都有很多条件(如是否、哪些、如何)打开表单,并且都运行良好,我将只映射事件处理程序名称与相应的菜单名称以触发菜单单击。但是有很多菜单和事件处理程序都在具有功能和所有功能的 mdiparent 中。这很讨厌。

标签: c# winforms


【解决方案1】:

在运行时检索事件处理程序并不容易,尤其是在 Forms 框架中,其中某些事件在后台有特殊处理。

一种更简单的方法(如果您在运行时不需要名称但在设计时需要)是在您的MyForm.designer.cs 文件上使用正则表达式来提取点击处理程序的名称。

请参阅此示例来源:

private void button1_Click(object sender, EventArgs e)
{
    string fileLocaton = @"C:Users
inebsource
eposWindowsFormsApp37WindowsFormsApp37Form1.Designer.cs";
    string fileContent = File.ReadAllText(fileLocaton);

    // Find all menu items in the designer file
    var matches = Regex.Matches(fileContent, @"System.Windows.Forms.ToolStripMenuItem (.+?);");
    foreach (Match match in matches)
    {
        string menuName = match.Groups[1].Value;
        textBox1.AppendText("Menuitem " + menuName + Environment.NewLine);

        // For each menu item, find all the event handlers
        var clickMatches = Regex.Matches(fileContent, 
            @"this." + Regex.Escape(menuName) + @".Click += new System.EventHandler(this.(.+?));");
        foreach (Match clickMatch in clickMatches)
        {
            string handlerName = clickMatch.Groups[1].Value;
            textBox1.AppendText("Eventhandler " + handlerName + Environment.NewLine);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多