OnPaint user control not working

Hi, I have a problem. I am writing a custom control. My control inherits from Windows.Forms.Control, and I'm trying to override the OnPaint method. The problem is rather strange, because it only works if I include one control in my form, if I add another control and the second does not get a draw, however, the OnPaint method is called for all the controls. So I want all my user controls to get a draw, not just my code:

If you run the code, you will see that only one red rectangle appears on 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)));



    }


}
+3
source share
2 answers

, - :

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

Graphic , Location . 0,0 .

, Pens , , "" , .

+2

LarsTech , , :

"" ( Windows), . 0, 0.

ClientSize ClientRectangle. , ( - Windows) : . / , ( , , ).

0

All Articles