Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Control OnPaint does not fire

I have the following custom Control:

public class Line : Control
{
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        using (var p = new Pen(Color.Black, 3))
        {
            var point1 = new Point(234, 118);
            var point2 = new Point(293, 228);
            e.Graphics.DrawLine(p, point1, point2);
        }
    }
}

And a Form where I add as new control a new instance of the Line class:

Controls.Add(new Line());

The problem is that the method OnPaint isn't called and no line is drawn. Why? How can i fix it?

like image 678
Nick Avatar asked Jun 05 '26 15:06

Nick


1 Answers

Your are not giving it a Size, try creating a Constructor and setting a default size there, you also seem to be using the parent controls coordinates, I would use the location of the Usercontrol to set your start position and only be concerned with the Width and Height of the control needed to contain your line.

public  Line()
{
     Size = new Size(500, 500);
}
like image 155
Mark Hall Avatar answered Jun 07 '26 23:06

Mark Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!