Search code examples
c#custom-controlsonpaint

Custom control onPaint event not working


Hey people I have a problem I am writing a custom control. My control inherits from Windows.Forms.Control and I am trying to override the OnPaint method. The problem is kind of weird because it works only if I include one control in my form if I add another control then the second one does not get draw, however the OnPaint method gets called for all the controls. So what I want is that all my custom controls get draw not only one here is my code:

If you run the code you will see that only one red rectangle appears in the screen.

public partial class Form1 : Form
{
    myControl one = new myControl(0, 0);
    myControl two = new myControl(100, 0);

    public Form1()
    {
        InitializeComponent();
        Controls.Add(one);
        Controls.Add(two);
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}


public class myControl:Control
{
    public myControl(int x, int y)
    {
        Location = new Point(x, y);
        Size = new Size(100, 20);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        Pen myPen = new Pen(Color.Red);
        e.Graphics.DrawRectangle(myPen, new Rectangle(Location, new Size(Size.Width -         1, Size.Height - 1)));



    }


}

Solution

  • I'm guessing you are looking for something like this:

    e.Graphics.DrawRectangle(Pens.Red, new Rectangle(0, 0, 
                                                    this.ClientSize.Width - 1,
                                                    this.ClientSize.Height - 1));
    

    Your Graphic object is for the interior of your control, so using Location isn't really effective here. The coordinate system starts at 0,0 from the upper-left corner of the client area of the control.

    Also, you can just use the built-in Pens for colors, otherwise, if you are creating your own "new" pen, be sure to dispose of them.