首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Winforms - Listbox - MouseHover -项目颜色

Winforms - Listbox - MouseHover -项目颜色
EN

Stack Overflow用户
提问于 2015-06-24 05:43:54
回答 2查看 1.3K关注 0票数 0

如何在winforms listbox中更改项目的颜色

我尝试使用MouseHover事件的listbox。但什么都没发生。

代码语言:javascript
运行
复制
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);
}
EN

回答 2

Stack Overflow用户

发布于 2015-06-24 09:08:44

我从这个answer得到了解决方案。

我们需要追踪这件事,

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2015-06-24 07:34:54

我认为问题可能在于你并没有真正改变你徘徊在上面的物品的颜色:

代码语言:javascript
运行
复制
lstNumbers.GetItemRectangle(index).Inflate(1, 2); //This is trying to inflate the item

你需要做点什么来改变颜色。

还有您可以使用的ItemMouseHover事件。类似于:

代码语言:javascript
运行
复制
private void lstNumbers_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
{
      e.Item.BackColor = Color.Green;
}

希望这对你有帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31018474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档