Search code examples
vb.netheightmenustrip

How to get height of individual buttons in a MenuStrip in VB.Net


I have a menu strip, that can have buttons added/removed. I want to be able to get the height of each individual button, and add them up. Is this possible?


Solution

  • I used this sample code as a guide: http://social.msdn.microsoft.com/Forums/vstudio/en-US/1a7f655b-fd14-4af9-b843-28432d8ce7fb/iterate-through-all-menu-options-in-a-menustrip

    The message box gives the Text for each ToolStripItem in MenuStrip1, followed by the height of the ToolStripItem in parenthesis. The bottom of the message box contains a total of the heights of all the controls in MenuStrip1.

    Is this what you are looking for?

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim total As Integer
        Dim menues As New List(Of ToolStripItem)
    
        For Each t As ToolStripItem In MenuStrip1.Items
            GetMenues(t, menues)
        Next
    
        Dim msg As New StringBuilder
        For Each t As ToolStripItem In menues
            msg.Append(t.Text)
            msg.Append(" (")
            msg.Append(t.Height)
            msg.AppendLine(")")
    
            total += t.Height
        Next
        msg.AppendLine("")
        msg.AppendLine("")
        msg.Append("Total Height: ")
        msg.Append(total)
    
        MessageBox.Show(msg.ToString)
    End Sub
    
    Public Sub GetMenues(ByVal Current As ToolStripItem, ByRef menues As List(Of ToolStripItem))
        menues.Add(Current)
        If TypeOf (Current) Is ToolStripMenuItem Then
            For Each menu As ToolStripItem In DirectCast(Current, ToolStripMenuItem).DropDownItems
                GetMenues(menu, menues)
            Next
        End If
    End Sub