【问题标题】:Winforms - Listbox - MouseHover - Item ColorWinforms - 列表框 - 鼠标悬停 - 项目颜色
【发布时间】:2015-06-24 05:43:54
【问题描述】:

winforms listbox987654322@ 中聚焦时如何更改项目的颜色?

我尝试了listboxMouseHover 事件。但是什么也没发生。

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);
}

【问题讨论】:

  • 您认为在您的代码中,着色发生了什么变化?另外:默认情况下,悬停和焦点不是一回事。最后:悬停不像您所期望的那样工作:当您在控件内移动鼠标时,它不会再次触发。也许 MouseMove 会更好地帮助你。但我不知道在什么..?
  • @TaW,有什么解决办法吗?也尝试了MouseMove,但没有任何反应。
  • 请参阅stackoverflow.com/q/1316027/292411,了解使用DrawMode 属性覆盖项目绘制的解决方案。
  • @C.Evenhuis,谢谢,我按照这个问题解决了我的问题。
  • '也尝试了 MouseMove,但没有任何反应。'当然。您的代码中没有“发生”的内容..

标签: c# .net winforms listbox


【解决方案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();
    }
  }
}

【讨论】:

    【解决方案2】:

    我认为问题可能在于您实际上并没有改变悬停项目的颜色:

    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;
    }
    

    希望对你有帮助!

    【讨论】:

    • 问题是关于 WINFORMS