简体   繁体   中英

C# drawing on custom controls

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM