c# listbox 添加图标和文字

给listbox 添加 DrawItem 事件

复制代码
        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            int index = e.Index;//获取当前要进行绘制的行的序号,从0开始。
            Graphics g = e.Graphics;//获取Graphics对象。
            Rectangle bound = e.Bounds;//获取当前要绘制的行的一个矩形范围。
            string text = listBox1.Items[index].ToString();//获取当前要绘制的行的显示文本。
            g.FillRectangle(new SolidBrush(Color.FromArgb(255, 255, 255)), e.Bounds);//绘制背景色。

            Font fn = new Font("宋体", 14);

            Image image = Properties.Resources.pengyou;  // 从资源管理器中读取图片

            int erea = 8;
            Rectangle imgRec = new Rectangle(bound.X + erea*2, bound.Y + erea, bound.Height - erea * 2, bound.Height - erea * 2);   // 图片区域
            Rectangle textRec = new Rectangle(imgRec.Right + 10, bound.Y, bound.Width - imgRec.Right,bound.Height);                 // 文字区域   

            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)  //如果当前行为选中行。
            {
                //绘制选中时要显示的蓝色边框。
                g.DrawRectangle(Pens.DodgerBlue, bound.Left, bound.Top, bound.Width - 1, bound.Height - 1);
                Rectangle rect = new Rectangle(bound.Left + 2, bound.Top + 2, bound.Width - 4, bound.Height - 4);

                //绘制选中时要显示的蓝色背景。
                g.FillRectangle(Brushes.DodgerBlue, rect);

                if (image != null)
                {
                    e.Graphics.DrawImage(image, imgRec, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
                }

                //绘制显示文本。
                TextRenderer.DrawText(g, text, fn, textRec, Color.White, TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
            }
            else
            {
                g.DrawRectangle(new Pen(Color.FromArgb(190, 190, 190)), bound.Left - 1, bound.Top, bound.Width + 1, bound.Height);
                
                if (image != null)
                {
                    e.Graphics.DrawImage(image, imgRec, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
                }

                TextRenderer.DrawText(g, text, fn, textRec, Color.Black, TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
            }
        }

运行效果

相关推荐
算法如诗7 小时前
**MATLAB R2025a** 环境下,基于 **双向时间卷积网络(BITCN)+ 双向长短期记忆网络(BiLSTM)** 的多特征分类预测完整实现
开发语言·网络·matlab
k09337 小时前
在组件外(.js文件)中使用pinia的方法2--在http.js中使用pinia
开发语言·javascript·http
二川bro7 小时前
第44节:物理引擎进阶:Bullet.js集成与高级物理模拟
开发语言·javascript·ecmascript
中文Python7 小时前
小白中文Python-双色球LSTM模型出号程序
开发语言·人工智能·python·lstm·中文python·小白学python
玩泥巴的7 小时前
.NET驾驭Excel之力:工作簿与工作表操作基础
c#·excel·二次开发·office·com互操作
越努力越幸运5087 小时前
JavaScript进阶篇垃圾回收、闭包、函数提升、剩余参数、展开运算符、对象解构
开发语言·javascript
czhc11400756637 小时前
C# 1116 流程控制 常量
开发语言·c#
葛小白17 小时前
C#进阶12:C#全局路径规划算法_Dijkstra
算法·c#·dijkstra算法
程序定小飞8 小时前
基于springboot的汽车资讯网站开发与实现
java·开发语言·spring boot·后端·spring
大米粥哥哥8 小时前
Qt 使用QAMQP连接RabbitMQ
开发语言·qt·rabbitmq·qamqp