Search code examples
vb.nettextmenuitemellipsismenustrip

How to add Ellipsis to MenuStrip Item Text


When using a MenuStrip, it's good to have the items and subitems have a certain width and that width should not change. Supposing the width does change to a great length, rather than changing the whole size of the MenuStrip Item to fit the text there should be a way to only display some of the text e.g. Ellipsis.

Before:

enter sdescription here

After

After

Clearly I edited the text of this MenuStrip MenuItem to demonstrate what I mean. Is this possible? if so how can I achieve this?


Solution

  • Public Class Form1
    
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim strPrograms(1, 4) '(0,*) = EXE name; (1,*) = screen name; (*,n) = Program Index
    
        strPrograms(0, 0) = "ONE.EXE" : strPrograms(1, 0) = "First"
        strPrograms(0, 1) = "TWO.EXE" : strPrograms(1, 1) = "Second"
        strPrograms(0, 2) = "THREE.EXE" : strPrograms(1, 2) = "Third program description is too long"
        strPrograms(0, 3) = "FOUR.EXE" : strPrograms(1, 3) = "Fourth"
        strPrograms(0, 4) = "FIVE.EXE" : strPrograms(1, 4) = "Fifth"
    
        Dim intMaxLength As Integer = 10
        Dim tsmParent As ToolStripMenuItem = MenuStrip1.Items.Add("Programs")
        For i As Integer = 0 To strPrograms.GetUpperBound(1)
          Dim strScreenName As String = strPrograms(1, i)
          If strScreenName.Length > intMaxLength Then
            strScreenName = strScreenName.Substring(0, intMaxLength - 1) & "…"
          End If
          Dim tsm As New ToolStripMenuItem(strScreenName)
          tsm.Tag = strPrograms(0, i)
          AddHandler tsm.Click, AddressOf tsm_Click
          tsmParent.DropDownItems.Add(tsm)
        Next i
    
      End Sub
    
      Private Sub tsm_Click(sender As Object, e As EventArgs)
        Dim strEXEName As String = DirectCast(sender, ToolStripMenuItem).Tag
        MsgBox(strEXEName)
    
      End Sub
    End Class