加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在OwnerDraw模式下ListBox DrawItem HotLight状态?

发布时间:2020-12-15 04:31:48 所属栏目:百科 来源:网络整理
导读:我在我的WinForms应用程序中使用OwnerDrawFixed作为DrawMode用于自定义ListBox控件. 当用户将鼠标悬停在列表框项目上时,我希望重新绘制ListBoxItem的背景(或执行其他操作),即在MouseMove … DrawItemState.HotLight永远不适用于ListBox,所以我想知道如何模拟
我在我的WinForms应用程序中使用OwnerDrawFixed作为DrawMode用于自定义ListBox控件.

当用户将鼠标悬停在列表框项目上时,我希望重新绘制ListBoxItem的背景(或执行其他操作),即在MouseMove …

DrawItemState.HotLight永远不适用于ListBox,所以我想知道如何模拟它,如何解决这个问题.

解决方法

我花了两年时间为你找到答案,但这里是:

DrawItemState.HotLight仅适用于所有者绘制的菜单,而不适用于列表框.对于ListBox,您必须自己跟踪项目:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读