Custom control onPaint event not working

2.4k views Asked by At

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)));



    }


}
2

There are 2 answers

1
LarsTech On BEST ANSWER

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.

0
Tergiver On

LarsTech beat me to it, but you should understand why:

All drawing inside of a control is made to a "canvas" (properly called a Device Context in Windows) who coordinates are self-relative. The upper-left corner is always 0, 0.

The Width and Height are found in ClientSize or ClientRectangle. This is because a window (a control is a window in Windows), has two areas: Client area and non-client area. For your borderless/titlebar-less control those areas are one and the same, but for future-proofing you always want to paint in the client area (unless the rare occasion occurs where you want to paint non-client bits that the OS normally paints for you).