如何在 winforms listbox
中关注项目时更改项目的颜色?
我尝试了MouseHover
的{{1}}事件。但没有任何反应。
listbox
答案 0 :(得分:1)
我从这个answer获得了解决方案。
我们需要跟踪项目,
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();
}
}
}
答案 1 :(得分:0)
我认为问题可能是你实际上没有改变你悬停的物品的颜色:
lstNumbers.GetItemRectangle(index).Inflate(1, 2); //This is trying to inflate the item
您需要做些什么来改变颜色。
您还可以使用ItemMouseHover
事件。类似的东西:
private void lstNumbers_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
{
e.Item.BackColor = Color.Green;
}
我希望这可以帮到你!