问题
See the two images below. I don't want each item in the menu to be the height of the largest. It should size to fit the contents. I've played around with a number of properties and haven't been able to prevent this behavior. Is it possible?
(source: blakerobertson.com)
(source: blakerobertson.com)
回答1:
Set MenuItem.OwnerDraw to true, then handle the MenuItem.MeasureItem event. This allows you to tell Windows Forms the size of this menu item independently of the size of others, albeit at the cost of having to then render the item yourself.
Note this does not result in automatic size-to-fit: you will need to use GDI+ functions to calculate the desired size.
回答2:
Old question but I had the same issue with a ToolStripMenuItem
shown for a NotifyIcon
. Solved setting AutoSize = False
, but it wasn't drawing the text well, I can't understand why. Then I had to draw it by my own handling its Paint event.
Private Sub OneMenuItem_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles OneMenuItem.Paint
If Me.DesignMode Then Return
Dim g As Graphics = e.Graphics
Dim it = OneMenuItem
Dim p = it.GetCurrentParent
Using b As New Drawing.SolidBrush(it.ForeColor)
g.DrawString(it.Text, it.Font, b, p.Padding.Left + 4 + it.Padding.Left, p.Padding.Top + 4 + it.Padding.Top)
End Using
End Sub
don't ask me what are those magic 4, they worked well comparing both drawn texts in DesignMode (it draws the text ok in design mode and you can compare).
VS2008, btw.
来源:https://stackoverflow.com/questions/2143757/how-do-you-make-height-of-context-menu-items-not-be-fixed-ie-scale-to-size-of-t