Winforms-列表框-鼠标悬停-项目颜色
本文关键字:项目 颜色 悬停 鼠标 Winforms- 列表 | 更新日期: 2023-09-27 17:59:33
在winformslistbox
中聚焦项目时,如何更改项目的颜色?
我尝试使用listbox
的MouseHover
事件。但什么也没发生。
private void lstNumbers_MouseHover(object sender, EventArgs e)
{
Point point = lstNumbers.PointToClient(Cursor.Position);
int index = lstNumbers.IndexFromPoint(point);
if (index < 0) return;
lstNumbers.GetItemRectangle(index).Inflate(1, 2);
}
我从这个答案中得到了解决方案。
我们需要跟踪这个项目,
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();
}
}
}
我认为问题可能是你没有真正改变悬停在上面的物品的颜色:
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;
}
我希望这对你有帮助!