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

运行效果

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值