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

运行效果

相关推荐
weixin_307779134 分钟前
PySpark实现GROUP BY WITH CUBE和WITH ROLLUP的分类汇总功能
大数据·开发语言·python·spark
信徒_13 分钟前
go 语言中的线程池
开发语言·后端·golang
Pandaconda13 分钟前
【Golang 面试题】每日 3 题(六十五)
开发语言·经验分享·笔记·后端·面试·golang·go
至暗时刻darkest14 分钟前
go 查看版本
开发语言·后端·golang
向哆哆28 分钟前
Java与NoSQL数据库的集成与优化
java·开发语言·nosql
MSTcheng.31 分钟前
【C语言】指针(5)
c语言·开发语言
╮壞孩子的天32 分钟前
C语言多人聊天室 ---chat(客户端聊天)
c语言·开发语言
pchmi32 分钟前
C#贪心算法
贪心算法·c#
IT猿手43 分钟前
2025高维多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
开发语言·人工智能·算法·机器学习·matlab·无人机·cocos2d
呱牛do it1 小时前
Python Matplotlib图形美化指南
开发语言·python·matplotlib