C#中使comboBox下拉列表显示图片

定义
  private System.Windows.Forms.ComboBox comboBox1;
  private System.Windows.Forms.ImageList imageList1;
comboBox1下面两个属性一定要设为下面的值。
DrawMode:OwnerDrawFixed;
DropDownStyle:DropDownList;
imageList1中一定要包函与所添加的项相同数目的图
关键方法,此方法为comboBox1的DrawItem事件所引起的方法。
private void comboBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
  {
   Graphics g = e.Graphics ;
   Rectangle r = e.Bounds ;
   Size imageSize = imageList1.ImageSize;
   Font fn = null ;
   if ( e.Index >= 0 )
   {
    fn = (Font)fontArray[0];
    string s = (string)comboBox1.Items[e.Index];
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Near;
    if ( e.State == ( DrawItemState.NoAccelerator | DrawItemState.NoFocusRect))
    {
     //画条目背景
     e.Graphics.FillRectangle(new SolidBrush(Color.Red) , r);
     //绘制图像
     imageList1.Draw(e.Graphics, r.Left, r.Top,e.Index);
     //显示字符串
     e.Graphics.DrawString( s , fn , new SolidBrush(Color.Black), r.Left+imageSize.Width ,r.Top);
     //显示取得焦点时的虚线框
     e.DrawFocusRectangle();
    }
    else
    {
     e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue) , r);
     imageList1.Draw(e.Graphics, r.Left, r.Top,e.Index);
     e.Graphics.DrawString( s , fn , new SolidBrush(Color.Black),r.Left+imageSize.Width ,r.Top);
     e.DrawFocusRectangle();
    }
   }
  }
 
 
向combobox中添加数据
comboBox1.Items.Add("小车");
   comboBox1.Items.Add("视频");
   comboBox1.Items.Add("信号灯");
posted @ 2007-04-11 00:24  随风而逝  阅读(7531)  评论(0编辑  收藏  举报