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

运行效果

相关推荐
董先生_ad986ad2 小时前
C# 中的 `lock` 关键字本质
开发语言·c#
元亓亓亓2 小时前
Java后端开发day36--源码解析:HashMap
java·开发语言·数据结构
道剑剑非道2 小时前
QT 打包安装程序【windeployqt.exe】报错c000007d原因:Conda巨坑
开发语言·qt·conda
小邓儿◑.◑3 小时前
C++武功秘籍 | 入门知识点
开发语言·c++
码银5 小时前
Java 集合:泛型、Set 集合及其实现类详解
java·开发语言
大G哥5 小时前
PHP标签+注释+html混写+变量
android·开发语言·前端·html·php
傻啦嘿哟5 小时前
HTTP代理基础:网络新手的入门指南
开发语言·php
fish_study_csdn5 小时前
pytest 技术总结
开发语言·python·pytest
爱编程的鱼6 小时前
C# 枚举(Enum)声明与使用详解
java·windows·c#
曹牧6 小时前
Java 调用webservice接口输出xml自动转义
java·开发语言·javascript