更改ListBox的颜色,高亮显示,背景大小?

时间:2018-06-06 07:56:14

标签: vb.net winforms listbox

https://i.imgur.com/2LTdcR2.png

所以我一直在搜索并设法突出显示ListBox中的值,但我正在尝试增加ListBox内文字的字体大小,但会产生以下图像如附:

enter image description here

这是我目前的代码:

Private Sub ListBox1_DrawItem(sender As System.Object, e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem

    e.DrawBackground()

    If ListBox1.Items(e.Index).ToString().Contains("*") Then
        e.Graphics.FillRectangle(Brushes.Red, e.Bounds)
    End If

    e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, Brushes.Black, New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y))
    e.DrawFocusRectangle()

我已经尝试搞乱“e.Bounds.X,e.Bounds.Y”以增加突出显示值的矩形/大小但似乎没有任何效果。

如何根据字体大小允许突出显示的矩形增加?

1 个答案:

答案 0 :(得分:1)

ListBox控件的DrawMode设置为OwnerDrawVariable或者在创建控件句柄后更改字体大小(即在已经处理{{1}之后)消息),您需要手动ItemHeigh属性设置为新的字体高度。

WM_MEASUREITEM属性设置为订阅ItemHeight MeasureItem事件并设置MeasureItemEventArgs ListBox属性。

此外,如果您动态更改字体大小 ,还需要强制将e.ItemHeight消息重新发送到WM_MEASUREITEM控件,否则物品界限不会更新 换句话说,当引发ListBox事件时,DrawItemEventArgs DrawItem属性会报告错误的措施。

强制e.Bounds控件重新测量其项目范围的方法是设置ListBox并立即将其重置为ListBox.DrawMode = DrawMode.Normal。这会导致再次处理OwnerDrawVariable消息。

WM_MEASUREITEM

在这里,我使用listBox1.DrawMode = DrawMode.Normal listBox1.DrawMode = DrawMode.OwnerDrawVariable listBox1.Update() 来衡量Font.Height事件中的当前ItemHeight,因为它会对该度量进行舍入。您可以使用TextRenderer.MeasureTextFont.GetHeight();你最终会得到相同的衡量标准,但是四舍五入。

MeasureItem

测试它调整字体大小:

Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem

    Dim ItemForeColor As Color
    Dim ItemBackColor As Color

    e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit

    If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
        ItemForeColor = Color.FromKnownColor(KnownColor.HighlightText)
        ItemBackColor = If(ListBox1.Items(e.Index).ToString().Contains("*"), Color.Red, Color.FromKnownColor(KnownColor.Highlight))
    Else
        ItemForeColor = ListBox1.ForeColor
        ItemBackColor = If(ListBox1.Items(e.Index).ToString().Contains("*"), Color.Red, ListBox1.BackColor)
    End If

    Using TextBrush As New SolidBrush(ItemForeColor)
        Using ItemBrush As New SolidBrush(ItemBackColor)
            e.Graphics.FillRectangle(ItemBrush, e.Bounds)
            e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), ListBox1.Font, TextBrush, e.Bounds, StringFormat.GenericTypographic)
        End Using
    End Using
    e.DrawFocusRectangle()
End Sub

Private Sub ListBox1_MeasureItem(sender As Object, e As MeasureItemEventArgs) Handles ListBox1.MeasureItem
    e.ItemHeight = ListBox1.Font.Height
End Sub

enter image description here