Wednesday, April 20, 2011

Setting background of WinForm ListBox

Does anyone know a method to insert a image in background into a ListBox in WinForms C#? Thanks for your attention. Nice Regards

From stackoverflow
  • 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.

    JayJay : Thanks Scraimer, that's all right i changed some lines but at the end that's work. Have a good time

0 comments:

Post a Comment