Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting background of WinForm ListBox

Tags:

c#

.net

winforms

Does anyone know a method to insert a image in background into a ListBox in WinForms C#?

like image 301
JayJay Avatar asked Dec 29 '25 07:12

JayJay


1 Answers

Well, you'll have to inherit a new control from ListBox. To to that, create a new project in your solution, of the type "Windows Control Library", and use the code below in the file control's source code file:

public partial class ListBoxWithBg : ListBox
{
   Image image;
   Brush brush, selectedBrush;

   public ListBoxWithBg()
   {
       InitializeComponent();

       this.DrawMode = DrawMode.OwnerDrawVariable;
       this.DrawItem += new DrawItemEventHandler(ListBoxWithBg_DrawItem);
       this.image = Image.FromFile("C:\\some-image.bmp");
       this.brush = new SolidBrush(Color.Black);
       this.selectedBrush = new SolidBrush(Color.White);
   }

   void ListBoxWithBg_DrawItem(object sender, DrawItemEventArgs e)
   {
       e.DrawBackground();
       e.DrawFocusRectangle();
       /* HACK WARNING: draw the last item with the entire image at (0,0) 
        * to fill the whole ListBox. Really, there's many better ways to do this,
        * just none quite so brief */
       if (e.Index == this.Items.Count - 1)
       {
           e.Graphics.DrawImage(this.image, new Point(0, 0));
       }
       else
       {
           e.Graphics.DrawImage(this.image, e.Bounds, e.Bounds, GraphicsUnit.Pixel);
       }
       Brush drawBrush = 
           ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
           ? this.selectedBrush : this.brush;
       e.Graphics.DrawString(this.Items[e.Index].ToString(), this.Font, drawBrush, e.Bounds);
   }
}

I omitted all the designer code and such for brevity, but you'll have to remember to Dispose of the Image and the Brushes in the Dispose method of the control.

like image 181
Shalom Craimer Avatar answered Dec 31 '25 20:12

Shalom Craimer