如何使用具有多个上下文菜单的每个循环? [英] How can I use for each loop with multiple context menus?

查看:80
本文介绍了如何使用具有多个上下文菜单的每个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用多个ContextMenu 控件可以使用 For Each 循环吗?



我尝试了什么:



我想做类似下面的例子...

There is any way to use For Each loop with multiple ContextMenu controls?

What I have tried:

I want to do something like the example bellow...

For Each lbl As Label In Me.Controls
    'Some code here...
Next



但是对于ContextMenu控件...


But for ContextMenu controls...

For Each cmenu As ContextMenu In ???

推荐答案

这是一个可行的解决方案,因为我从 stackoverflow.com 这里



如果您使用的ContextMenuStrip类替换并添加了以前版本的ContextMenu控件的功能,您可以使用类似的代码:

Here is a working solution as I got it from stackoverflow.com here:

If you are using the ContextMenuStrip class which replaces and adds functionality to the ContextMenu control of previous versions, you can use a similar code:
For Each x As Object In Me.components.Components
    If TypeOf x Is ContextMenuStrip Then
        MsgBox(CType(x, ContextMenuStrip).Name)
    End If
Next x

你需要你se反射,以便在应用程序拥有的开放表单集合中查找每个ContextMenuStrip。

You need to use Reflection in order to find every ContextMenuStrip in the collection of open forms owned by the application.

For Each frm As Form In My.Application.OpenForms
    For Each fi As System.Reflection.FieldInfo In frm.GetType.GetFields(
        System.Reflection.BindingFlags.NonPublic Or _
        System.Reflection.BindingFlags.Instance Or _
        System.Reflection.BindingFlags.DeclaredOnly)
        If fi.FieldType Is GetType(ContextMenuStrip) Then
            MsgBox(frm.Name & " - " & TryCast(fi.GetValue(frm), ContextMenuStrip).Name)
        End If
    Next fi
Next frm

如果我们使用 MetroContextMenu 控件,我们应该将每个:

And in case we use a MetroContextMenu control, we should replace every:

ContextMenuStrip

替换为:

MetroFramework.Controls.MetroContextMenu


如果我没记错,每个上下文菜单都与一个特定的控件相关联,所以要获得上下文菜单,你还需要迭代控件,然后检查每个控件,看它是否有与之关联的ContextMenu(即,ContextMenu是Nothing)。
If I recall correctly, each context menu is associated with a particular control, so to get the context menu you still need to iterate over the controls and then you check each control to see if it has a ContextMenu associated with it or not (i.e., the ContextMenu is Nothing).


这篇关于如何使用具有多个上下文菜单的每个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆