Does anyone know a method to insert a image in background into a ListBox in WinForms C#?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With