在.Net 中,如何使上下文菜单项的高度不固定(即缩放到特定项目的大小)?

发布于 2024-08-19 15:20:29 字数 627 浏览 1 评论 0原文

请参阅下面的两张图片。我不希望菜单中的每个项目都是最大的高度。它的大小应该适合内容。我尝试过许多属性,但无法阻止这种行为。是否可以?

所需高度
(来源:blakerobertson.com

全部固定高度!
(来源:blakerobertson.com

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?

Desired Height
(source: blakerobertson.com)

Fixed Height For all!
(source: blakerobertson.com)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2024-08-26 15:20:29

MenuItem.OwnerDraw 设置为 true ,然后处理 MenuItem.MeasureItem 事件。这允许您告诉 Windows 窗体该菜单项的大小,而与其他菜单项的大小无关,尽管代价是必须自己渲染该菜单项。

请注意,这不会导致自动调整尺寸:您将需要使用 GDI+ 函数来计算所需的尺寸。

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.

请爱~陌生人 2024-08-26 15:20:29

老问题,但我对为 NotifyIcon 显示的 ToolStripMenuItem 遇到了同样的问题。解决了设置 AutoSize = False 的问题,但它没有很好地绘制文本,我不明白为什么。然后我必须通过自己处理 Paint 事件来绘制它。

    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

不要问我那些魔法 4 是什么,它们在比较设计模式中绘制的文本时效果很好(它在设计模式下绘制文本正常,您可以进行比较)。
VS2008,顺便说一句。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文