前提:Combobox的【DrawMode】属性设置为【OwnerDrawFixed】,DrawItem事件绑定下边的方法。
Tips:可以多个Combobox同时绑定此方法哦~。
Private Sub Combobox_DrawItem(sender As Object, e As DrawItemEventArgs) Handles Combobox1.DrawItem, Combobox2.DrawItem, Combobox3.DrawItem, Combobox4.DrawItem, Combobox5.DrawItem, Combobox6.DrawItem
If e.Index < 0 Then Exit Sub
Dim cmb = CType(sender, ComboBox)
Dim ft = cmb.Font
Dim itemText = cmb.GetItemText(cmb.Items(e.Index))
Dim ss = e.Graphics.MeasureString(itemText, ft)
Dim left = 0
'中央揃え
left = (e.Bounds.Width - ss.Width) / 2
If left < 0 Then
left = 0
End If
'色の設定
Dim TextBrush As Brush
If e.State And DrawItemState.Selected Then
TextBrush = Brushes.White
Else
TextBrush = Brushes.Black
End If
e.DrawBackground()
e.Graphics.DrawString(itemText, ft, TextBrush, New RectangleF(e.Bounds.X + left, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), StringFormat.GenericDefault)
e.DrawFocusRectangle()
End Sub