Reputation: 1325
I played with some custom Controls created by me and I wanted to draw some Graphics for them.
I achieved everything I wanted but I have a question because something seems strange to me. I tried for example to make a new control like this:
public class Square : Control
{
public Square(Point location)
{
this.Size = new Size(100, 100);
this.Location = location;
Draw();
}
public void Draw()
{
Graphics g = this.CreateGraphics();
g.DrawRectangle(Pens.Black, 5, 5, 20, 20);
}
}
This doesn't draw anything, but, if I call the "Draw" method from another action like a button press on the form it works. It also works if I override the OnPaint method of my control and call the "Draw" method here. (I know that I should make all the drawing in the Paint/OnPaint but I did this just to try other things)
What's the difference ? Why can't I just call my "Draw" method anywhere I want?
Upvotes: 0
Views: 145
Reputation: 15982
When you call Draw()
method in constructor, the control has not yet been added to the parent, is just an object in memory, so the call has no effect.
If you make the call as you say in the OnPaint()
method, then is drawed since this method is called whenever render the control is needed.
Upvotes: 1