ListBox DrawItem HotLight State in OwnerDraw?

I am using OwnerDrawFixed as DrawMode for a custom ListBox in my WinForms application.

I want to redraw the background (or do some other action) of the ListBoxItem when the user is hovering over a list item, that is, MouseMove ...

DrawItemState.HotLight never works for a ListBox, so I'm wondering how to emulate it, how to solve this problem.

+7
c # winforms listbox ownerdrawn
source share
2 answers

It took me only two years to find the answer for you, but here it is:

DrawItemState.HotLight applies only to owner lists, not to a list. For a ListBox, you must track this element yourself:

 public partial class Form1 : Form { private int _MouseIndex = -1; public Form1() { InitializeComponent(); } private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { Brush textBrush = SystemBrushes.WindowText; if (e.Index > -1) { if (e.Index == _MouseIndex) { e.Graphics.FillRectangle(SystemBrushes.HotTrack, e.Bounds); textBrush = SystemBrushes.HighlightText; } else { if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); textBrush = SystemBrushes.HighlightText; } else e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds); } e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, textBrush, e.Bounds.Left + 2, e.Bounds.Top); } } private void listBox1_MouseMove(object sender, MouseEventArgs e) { int index = listBox1.IndexFromPoint(e.Location); if (index != _MouseIndex) { _MouseIndex = index; listBox1.Invalidate(); } } private void listBox1_MouseLeave(object sender, EventArgs e) { if (_MouseIndex > -1) { _MouseIndex = -1; listBox1.Invalidate(); } } } 
+11
source share

This solution will just damage your code; just try this:

 If e.State And DrawItemState.Selected Then e.Graphics.FillRectangle(SystemBrushes.HotTrack, e.Bounds) e.Graphics.DrawString(drv, Me.Font, SystemBrushes.HighlightText, e.Bounds.X + 18, e.Bounds.Y + 1) Else e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds) e.Graphics.DrawString(drv, Me.Font, SystemBrushes.ControlText, e.Bounds.X + 18, e.Bounds.Y + 1) End If 

This operation: e.State And DrawItemState.Selected verifies that the element is frozen. No need to put a whole package of code to know that the element is hanging.

0
source share

All Articles