WinForm中ComboBox的DrawItem事件的应用
今天在CSDN的论坛看到一个问题,大致是这么个意思:
当鼠标滑过ComboBox的列表项时,怎么才能获取当前鼠标滑过列表项?
在网上找了找,没现成的,但是看到有人在VC里边用OnDrawItem来实现,就用了这个思路。
首先将将DrawMode属性设置为OwnerDrawFixed
然后绑定DrawItem事件,具体方法如下:
- private void moveComboBox1_DrawItem(object sender, DrawItemEventArgs e)
- {
- //经测试,鼠标划过时,e.State 为 DrawItemState.Selected
- if (e.State == DrawItemState.Selected)
- {
- e.Graphics.FillRectangle(new SolidBrush(Color.Beige), new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
- //显示鼠标滑过项目的文本
- label1.Text = moveComboBox1.Items[e.Index].ToString();
- }
- else if (e.State == DrawItemState.None)
- {
- e.Graphics.FillRectangle(new SolidBrush(Color.White), new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
- }
- e.Graphics.DrawString(moveComboBox1.Items[e.Index].ToString(), moveComboBox1.Font, new SolidBrush(Color.Black), 2, e.Bounds.Y + 2);
- }