C# Winform编程ListBox之添加图标

 先上图:

 

这里添加固定的图片的。

代码:

 

  1. private Color RowBackColorAlt=Color.FromArgb(200,200,200);//交替色 
  2. private Color RowBackColorSel = Color.FromArgb(150, 200, 250);//选择项目颜色 
  3.  
  4. public Form1() 
  5.     InitializeComponent();             
  6.     listBox1.DrawMode = DrawMode.OwnerDrawFixed; 
  7.     listBox1.ItemHeight = 24; 
  8.  
  9. private void listBox1_DrawItem(object sender, DrawItemEventArgs e) 
  10.     Brush myBrush = Brushes.Black; 
  11.  
  12.     if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
  13.     { 
  14.         myBrush = new SolidBrush(RowBackColorSel); 
  15.     } 
  16.     else if (e.Index % 2 == 0) 
  17.     { 
  18.         myBrush = new SolidBrush(RowBackColorAlt); 
  19.     } 
  20.     else 
  21.     { 
  22.         myBrush = new SolidBrush(Color.White); 
  23.     } 
  24.     e.Graphics.FillRectangle(myBrush, e.Bounds); 
  25.     e.DrawFocusRectangle();//焦点框 
  26.  
  27.     //绘制图标 
  28.     Image image = Image.FromFile("images/item.png"); 
  29.     Graphics g = e.Graphics; 
  30.     Rectangle bounds = e.Bounds; 
  31.     Rectangle imageRect = new Rectangle( 
  32.         bounds.X, 
  33.         bounds.Y, 
  34.         bounds.Height, 
  35.         bounds.Height); 
  36.     Rectangle textRect = new Rectangle( 
  37.         imageRect.Right, 
  38.         bounds.Y, 
  39.         bounds.Width - imageRect.Right, 
  40.         bounds.Height); 
  41.  
  42.     if (image != null
  43.     { 
  44.         g.DrawImage( 
  45.             image, 
  46.             imageRect, 
  47.             0, 
  48.             0, 
  49.             image.Width, 
  50.             image.Height, 
  51.             GraphicsUnit.Pixel); 
  52.     } 
  53.  
  54.     //文本 
  55.     StringFormat strFormat = new StringFormat(); 
  56.     //strFormat.Alignment = StringAlignment.Center; 
  57.     strFormat.LineAlignment = StringAlignment.Center; 
  58.     e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), textRect,strFormat); 
posted @   郑文亮  阅读(7154)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
历史上的今天:
2012-06-07 XCode4.2iOS各模板简述
点击右上角即可分享
微信分享提示