You need to enable JavaScript to run this app. 递归提取ContextMenuStrip的ToolStripMenuItem并跳过ToolStripSeparator
优惠活动
大模型
产品
解决方案
定价
更多

递归提取ContextMenuStrip的ToolStripMenuItem并跳过ToolStripSeparator

功能实现需求与现存问题
  • 核心目标:提取DataGridView关联ContextMenuStrip下的所有有效菜单项,存入List(Of ToolStripMenuItem)集合;递归抓取全层级菜单项的Name、Text属性存入结果字典,遍历过程需排除所有ToolStripSeparator类型的分隔项
  • 已完成的前置逻辑:
    • 实现FindControlRecursive递归遍历方法,可扫描当前窗体下所有控件,将筛选出的DataGridView实例存入List(Of Control)集合
    • 逐筛选出的已命名DataGridView控件,取出其关联的ContextMenuStrip引用,遍历顶层ToolStripItem集合,遇到有效ToolStripMenuItem时初始化存储集合,调用自定义递归方法FindControlRecursive_ContextMenu收集目标菜单项及其所有下级子菜单
  • 现存缺陷:递归遍历DropDown.Items子项集合时,若集合内混有ToolStripSeparator类型项,会因不当类型转换触发异常,无法实现自动跳过分隔项、顺序处理后续子项的逻辑
遍历逻辑优化方案

核心修正思路是在遍历所有层级的ToolStripItem集合时,先做类型判断、再做类型转换,从根源避免强转异常:

  • 遍历每个ToolStripItem集合元素时,首先判断当前项类型,若为ToolStripSeparator直接跳过,不做后续处理
  • 对非分隔项,用TryCast做安全类型转换,仅当转换为ToolStripMenuItem成功时,才将项加入目标集合,再递归遍历该项的所有下级DropDown子项
  • 对其他非目标类型的ToolStripItem(如嵌入的控件类项),因TryCast转换结果为Nothing,会自动跳过,不会触发异常

优化后的递归收集方法参考:

Private Sub CollectAllMenuItems(sourceItems As ToolStripItemCollection, menuStore As List(Of ToolStripMenuItem))
    For Each currentItem As ToolStripItem In sourceItems
        ' 优先跳过分隔项
        If TypeOf currentItem Is ToolStripSeparator Then
            Continue For
        End If
        ' 安全类型转换,避免强转异常
        Dim menuItem = TryCast(currentItem, ToolStripMenuItem)
        If menuItem IsNot Nothing Then
            menuStore.Add(menuItem)
            ' 存在下级菜单时递归遍历
            If menuItem.HasDropDownItems Then
                CollectAllMenuItems(menuItem.DropDown.Items, menuStore)
            End If
        End If
    Next
End Sub
全流程串联逻辑
  1. 从已收集的DataGridView实例中,取出其关联的ContextMenuStrip引用
  2. 初始化空的List(Of ToolStripMenuItem)集合,调用上述递归方法,从ContextMenuStrip的顶层Items集合开始全量遍历收集
  3. 遍历完成后,循环读取集合内每个菜单项的Name、Text属性,写入预先定义的Dictionary(Of String, String)结果字典即可

内容的提问来源于stack exchange,提问作者Matteo Scattolin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 06:36:01