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

来源:互联网 发布:2路视频加网络光端机 编辑:程序博客网 时间:2024/05/07 05:30
定义:
  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(); 
    } 
   }
  }

   comboBox1.Items.Add("小车"); 
   comboBox1.Items.Add("视频"); 
   comboBox1.Items.Add("信号灯"); 
0 0
原创粉丝点击