答: ListBox.SelectedIndex
非常不合理(就像汉斯说的那样),但e.ForeColor
足够正确。改用那个。
替换您的代码:e.Index == ((ListBox)sender).SelectedIndex
和e.ForeColor == SystemColors.HighlightText
支持数据:
将此行添加到顶部listBox1_DrawItem
:
Console.WriteLine("e.Index=" + e.Index + " SelectedIndex=" +
listBox1.SelectedIndex + " ForeColor=" + e.ForeColor);
它产生这样的输出(//注释)
// Added 4 items to listbox
e.Index=0 SelectedIndex=-1 ForeColor=Color [WindowText]
e.Index=1 SelectedIndex=-1 ForeColor=Color [WindowText]
e.Index=2 SelectedIndex=-1 ForeColor=Color [WindowText]
e.Index=3 SelectedIndex=-1 ForeColor=Color [WindowText]
// MouseDown on item 0
e.Index=0 SelectedIndex=-1 ForeColor=Color [WindowText]
e.Index=0 SelectedIndex=0 ForeColor=Color [HighlightText]
e.Index=0 SelectedIndex=0 ForeColor=Color [HighlightText]
e.Index=0 SelectedIndex=0 ForeColor=Color [HighlightText]
e.Index=0 SelectedIndex=0 ForeColor=Color [HighlightText]
e.Index=0 SelectedIndex=0 ForeColor=Color [HighlightText]
e.Index=1 SelectedIndex=0 ForeColor=Color [WindowText]
e.Index=2 SelectedIndex=0 ForeColor=Color [WindowText]
e.Index=3 SelectedIndex=0 ForeColor=Color [WindowText]
e.Index=0 SelectedIndex=0 ForeColor=Color [HighlightText]
// MouseUp on item 0 (no DrawItem events)
// MouseDown for item 1
e.Index=0 SelectedIndex=0 ForeColor=Color [HighlightText]
e.Index=0 SelectedIndex=0 ForeColor=Color [WindowText]
e.Index=1 SelectedIndex=1 ForeColor=Color [HighlightText]
e.Index=1 SelectedIndex=1 ForeColor=Color [HighlightText]
// MouseUp for item 1 (no DrawItem events)
// MouseDown for item 2
e.Index=1 SelectedIndex=1 ForeColor=Color [HighlightText]
e.Index=1 SelectedIndex=1 ForeColor=Color [WindowText]
e.Index=2 SelectedIndex=2 ForeColor=Color [HighlightText]
e.Index=2 SelectedIndex=2 ForeColor=Color [HighlightText]
// Drag to item 3
e.Index=2 SelectedIndex=2 ForeColor=Color [HighlightText]
e.Index=2 SelectedIndex=2 ForeColor=Color [WindowText]
e.Index=3 SelectedIndex=3 ForeColor=Color [HighlightText]
e.Index=3 SelectedIndex=3 ForeColor=Color [HighlightText]
// MouseUp over item 3 (no DrawItem events)
所以基本上...... ListBox 绘制的可能比我们想要的要多,但您最终会在最后一次绘制时获得正确的颜色。
我还推荐DoubleBuffering。