ff

WinForm中ComboBox的DrawItem事件的应用

WinForm中ComboBox的DrawItem事件的应用

2008年11月24日 2,208 Views

今天在CSDN的论坛看到一个问题,大致是这么个意思:
当鼠标滑过ComboBox的列表项时,怎么才能获取当前鼠标滑过列表项?

在网上找了找,没现成的,但是看到有人在VC里边用OnDrawItem来实现,就用了这个思路。
首先将将DrawMode属性设置为OwnerDrawFixed
然后绑定DrawItem事件,具体方法如下:

  1. private void moveComboBox1_DrawItem(object sender, DrawItemEventArgs e)
  2. {
  3.             //经测试,鼠标划过时,e.State 为 DrawItemState.Selected
  4.             if (e.State == DrawItemState.Selected)
  5.             {
  6.                 e.Graphics.FillRectangle(new SolidBrush(Color.Beige), new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
  7.                 //显示鼠标滑过项目的文本
  8.                 label1.Text = moveComboBox1.Items[e.Index].ToString();
  9.             }
  10.             else if (e.State == DrawItemState.None)
  11.             {
  12.                 e.Graphics.FillRectangle(new SolidBrush(Color.White), new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
  13.             }
  14.  
  15.             e.Graphics.DrawString(moveComboBox1.Items[e.Index].ToString(), moveComboBox1.Font, new SolidBrush(Color.Black), 2, e.Bounds.Y + 2);
  16. }
posted @ 2009-07-02 11:39  人在旅途,前行  阅读(1159)  评论(0编辑  收藏  举报