Results 1 to 3 of 3

Thread: [RESOLVED] Is there a Collection for ContextMenuStrips?

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jun 2018
    Location
    Krähental
    Posts
    64

    Resolved [RESOLVED] Is there a Collection for ContextMenuStrips?

    When a form loads I can iterate through the controls in a for each loop looking for specific types. But this never includes ContextMenuStrips.

    If, for example, I wanted to change the font used by contextmenus at runtime how do I find them? Of course I could code each one individually and that works. But is there a collection I can iterate through looking for them?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,302

    Re: Is there a Collection for ContextMenuStrips?

    Each control or component you add in the designer has a field generated for it by default. You can get the value of each field whose type is ContextMenuStrip like so:
    vb.net Code:
    1. Imports System.Reflection
    2.  
    3. Public Class Form1
    4.  
    5.     Private contextMenuStrips As ContextMenuStrip()
    6.  
    7.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    8.         Dim fields = Me.GetType().GetFields(BindingFlags.NonPublic Or
    9.                                             BindingFlags.Instance Or
    10.                                             BindingFlags.DeclaredOnly)
    11.  
    12.         contextMenuStrips = fields.Where(Function(fi) fi.FieldType Is GetType(ContextMenuStrip)).
    13.                                    Select(Function(fi) fi.GetValue(Me)).
    14.                                    Cast(Of ContextMenuStrip)().
    15.                                    ToArray()
    16.     End Sub
    17.  
    18. End Class

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Jun 2018
    Location
    Krähental
    Posts
    64

    Re: Is there a Collection for ContextMenuStrips?

    That does it. Thank you very much.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width