Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually get instance of Graphics object in WinForms?

I know how to work with object of type Graphics (at least I am able to render images) but I always do that by passing graphics object retrieved from OnPaint method.

I would like to display an image when the app is opened (ie in Form_Load method) but have no clue how to obtain the instance of Graphics object I could use? Thanks

like image 495
Lojol Avatar asked Jan 21 '11 14:01

Lojol


2 Answers

Using the e.Graphics object that OnPaint() supplies to you is the correct way of doing it. It will run right after the OnLoad() method. The form isn't visible yet in OnLoad.

Getting a Graphics object from Control.CreateGraphics() is supported. However, whatever you draw with this will be wiped out as soon as the form repaints itself. Which happens when the user moves another window across yours (pre-Aero) or when she minimizes and restores or otherwise resizes the window. Use CreateGraphics only ever when animating at a high rate.

like image 154
Hans Passant Avatar answered Oct 04 '22 15:10

Hans Passant


If you're attempting to create a graphics object from the surface of your form, you can use this.CreateGraphics

If you are attempting to create a new Image, you can always initialize an Image and then call Graphics.CreateGraphics.FromImage(YourImage) e.g.

Bitmap b = new Bitmap(100,100);
var g = Graphics.CreateGraphics.FromImage(b);

At this point, any drawing performed to your Graphics object will be drawn onto your image.

like image 24
George Johnston Avatar answered Oct 04 '22 17:10

George Johnston