Reputation: 124
so I've created a custom control and I wanted to draw on that control now the problem is that I can't use OnPaint event because I want to draw at different times with different conditions.
here is the custom control function to draw a rectangle
public void DrawARectangle(int x,int y,int height,int width)
{
Graphics g = this.CreateGraphics();
g.DrawRectangle(Pens.Black, x, y, height, width);
g.FillRectangle(Brushes.Black, x, y, height, width);
}
and I basically call it from my form , but it doesn't draw anything even after using the update() method.
Upvotes: 1
Views: 3767
Reputation: 54433
Graphics g = this.CreateGraphics();
This is almost always wrong.
Use the Paint/OnPaint
event and its e.Graphics
parameter! Store the coordinates somewhere and be prepared to always draw everthing..
I can't use OnPaint event because I want to draw at different times with different conditions. Yes. But you must!
This is how graphics work in winforms. This only sounds wasteful but..: The system also needs to call this event when the window must be restored, so there is no way around it if you want your drawing to persist..
Only non-persistent graphics operations like displaying a dynamic rubber-band rectangle or a line that follows the mouse, are ok with a Graphics
object you get from control.CreateGraphics()
. And measurements without drawing...
Trigger re-drawing by calling Invalidate
on your control whenever your data have changed.
Upvotes: 1
Reputation: 1368
You must use Control.OnPaint
to do your custom drawing. Otherwise all of your drawings will be erased after the next repaint of your control.
The idea is you may store your rectangles in a list. Then in your Control.OnPaint
, you do the drawing based on that list.
Upvotes: 2