Results 1 to 3 of 3

Thread: How to delete menuItems and their Handlers?

  1. #1

    Thread Starter
    Hyperactive Member jonwondering's Avatar
    Join Date
    May 2005
    Posts
    311

    Unhappy How to delete menuItems and their Handlers?

    Hey everybody, I have a little problem and I can't figure it out. I got a memory leak... Let's say I have a txt file with the following values in there:

    Red
    Green
    Blue

    My program reads in those values every 10 seconds and stores them as a menu in a ContextMenu control. I have done that with a timer (obviously) and everytime before it loads the items in a menu, it clears the menu (so that the menuitems would not pile up).

    Here's the code inside the loop:

    VB Code:
    1. Dim Z As MenuItem
    2. While ("... Not the end of file ...")
    3.             ' Here 'Temp' stores the name of the color
    4.             Z = New MenuItem(Temp)
    5.             Me.ContextMenu1.MenuItems.Add(Z)
    6.             AddHandler Z.Click, AddressOf Implement_Click
    7. End While
    8.  
    9. Private Sub Implement_Click(ByVal Sender As Object, ByVal e As EventArgs) Handles Z.Click
    10.             MsgBox("You clicked here")
    11. End Sub

    The problem is that every time the loop executes, it creates new MenuItems and new Handlers for them, making the memory usage of the program increase...

    Does anybody know how I can delete those MenuItems and their Handlers to free up that space?
    (The problem is that they are created dynamically...)

    Thanks,
    Jon
    Last edited by jonwondering; May 11th, 2005 at 10:25 AM.

  2. #2
    Lively Member
    Join Date
    Jun 2004
    Posts
    99

    Re: How to delete menuItems and their Handlers?

    Would this take care of it? I used an array to simulate the file, and just put the code in a button click for testing. It seemed to work with repeated runs.

    Code:
            Dim Temp As String() = {"Red", "Blue", "Green"}
            Dim Z As MenuItem
    
            While Me.ContextMenu.MenuItems.Count > 0
                Me.ContextMenu.MenuItems(0).Dispose()
            End While
    
            For i As Integer = 0 To Temp.Length - 1
                Z = New MenuItem(Temp(i))
                Me.ContextMenu1.MenuItems.Add(Z)
                AddHandler Z.Click, AddressOf Implement_Click
            Next

    Also, I got rid of the 'Handles Z.Click' at the end of the Implement_Click (since you are attaching it in code).

  3. #3

    Thread Starter
    Hyperactive Member jonwondering's Avatar
    Join Date
    May 2005
    Posts
    311

    Re: How to delete menuItems and their Handlers?

    Yes that works well.

    Thank you very much,
    Jon

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