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);
            }
        }

运行效果

相关推荐
sunny.day2 分钟前
js原型与原型链
开发语言·javascript·原型模式·js原型链
weixin_523185324 分钟前
Java内存模型详解:栈、堆、方法区、本地方法栈与程序计数器
java·开发语言
换个昵称都难18 分钟前
WebRTC QoS 实战:从原理到弱网优化
开发语言·php·webrtc
小满Autumn26 分钟前
固高GTS运动控制卡 — C#开发完全指南
c#·.net·上位机·运动控制卡
爱吃生蚝的于勒26 分钟前
QT开发第三章——常用控件
linux·服务器·开发语言·前端·javascript·c++·qt
未若君雅裁30 分钟前
工厂模式详解:简单工厂、工厂方法与抽象工厂
java·开发语言
我命由我1234538 分钟前
由 ImageView 获取到的 Drawable 对象,它的 intrinsicWidth、intrinsicWidth 与实际图片的尺寸
java·开发语言·java-ee·android studio·android jetpack·android-studio·android runtime
xuankuxiaoyao39 分钟前
Axios-图书列表案例
开发语言·前端·javascript
guslegend41 分钟前
Java 创建对象有几种方式
java·开发语言
影寂ldy42 分钟前
C# 多播委托
前端·javascript·c#