2

I need your help in following question (using .Net 3.5 and Windows Forms):

I just simply want to draw a line on a middle of a combobox (Windows Forms) that is situated on a form. The code I use is:

void comboBox1_Paint(object sender, PaintEventArgs e)
{
  e.Graphics.DrawLine(new Pen(Brushes.DarkBlue),
                      this.comboBox1.Location.X,
                      this.comboBox1.Location.Y + (this.comboBox1.Size.Height / 2),
                      this.comboBox1.Location.X + this.comboBox1.Size.Width,
                      this.comboBox1.Location.Y + (this.comboBox1.Size.Height / 2));
}

To fire a paint event:

private void button1_Click(object sender, EventArgs e)
{
  comboBox1.Refresh();
}

When I execute the code and press button the line isn't drawn. In debug the breakpoint at the paint handler isn't being hit. The strange thing is that on MSDN there is a paint event in ComBox's events list, but in VS 2010 IntelliSense doesn't find such event in ComboBox's members

Thanks.

westwood
  • 1,774
  • 15
  • 29

2 Answers2

2
public Form1() 
{
  InitializeComponent();
  comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
  comboBox1.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem);
}

void comboBox1_DrawItem(object sender, DrawItemEventArgs e) {
  e.DrawBackground();
  e.Graphics.DrawLine(Pens.Black, new Point(e.Bounds.Left, e.Bounds.Bottom-1),
    new Point(e.Bounds.Right, e.Bounds.Bottom-1));
  TextRenderer.DrawText(e.Graphics, comboBox1.Items[e.Index].ToString(), 
    comboBox1.Font, e.Bounds, comboBox1.ForeColor, TextFormatFlags.Left);
  e.DrawFocusRectangle();
}
Jaime Oro
  • 9,899
  • 8
  • 31
  • 39
  • thanks it's worked! Can you please answer another little question? I replaced DrawLine with DrawImage and I want to draw animated gif (something like wait animation) but it drawn only in static, not animatng, what can I use to draw animated images? – westwood Aug 08 '12 at 11:04
  • I think you should use a PictureBox as explained in [this early question](http://stackoverflow.com/questions/165735/how-do-you-show-animated-gifs-on-a-windows-form-c). – Jaime Oro Aug 08 '12 at 11:25
1

Paint event will not fire.
What do you want is possible only when DropDownStyle == ComboBoxStyle.DropDownList:

        comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
        comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        comboBox1.DrawItem += (sender, args) => 
        {
            var ordinate = args.Bounds.Top + args.Bounds.Height / 2;
            args.Graphics.DrawLine(new Pen(Color.Red), new Point(args.Bounds.Left, ordinate),
                new Point(args.Bounds.Right, ordinate));
        };

This way you can draw selected item area yourself.

Dennis
  • 37,026
  • 10
  • 82
  • 150