7

OwnerDrawFixedWinFormsアプリのカスタムリストボックスコントロールのDrawModeとして使用しています。

ユーザーがリストボックスアイテムにカーソルを合わせたとき、つまりMouseMoveで、ListBoxItemの背景を再描画(または他のアクションを実行)したい...

DrawItemState.HotLightListBoxで機能することはないので、どのようにエミュレートするか、この問題を回避する方法を考えます。

4

2 に答える 2

11

あなたの答えを見つけるのに2年しかかかりませんでしたが、ここにあります:

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();
    }
  }
}
于 2011-08-05T03:45:37.793 に答える