How to manually get an instance of a Graphics object in WinForms?

I know how to work with an object of type Graphics (at least I can display images), but I always do this by passing in a graphic object obtained from the OnPaint method.

I would like to display the image when the application is opened (i.e. in the Form_Load method), but has no idea how to get an instance of the Graphics object that I could use? Thanks

+7
source share
5 answers

Using the e.Graphics object that OnPaint () provides you with is the right way to execute it. It will start immediately after the OnLoad () method. The form is not yet visible in OnLoad.

Getting a Graphics object from Control.CreateGraphics () is supported. However, what you draw with this will be destroyed as soon as the shape is repainted. This happens when the user moves another window on your (pre-Aero) or when it minimizes and restores or otherwise resizes the window. Use CreateGraphics only when animating at high speed.

+12
source

If you are trying to create a graphic object from the surface of your form, you can use this.CreateGraphics

If you are trying to create a new image, you can always initialize Image and then call Graphics.CreateGraphics.FromImage(YourImage) for example.

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

At this point, any drawing made for your Graphics object will be drawn on your image.

+2
source

And how do you plan to use the Graphics object that you received in the Load event?

If you want to draw something on the screen, you must be in the Paint event, or it will be cleared on the next paint.

What you can do: upload another (simple) form using just the image and hide it when the main form loads.

Since your load event is likely to work in the user interface thread. Call DoEvents to display another form.

0
source

None of the previous answers worked for me. I found an effective solution by Rajnant Rajwadi (see https://social.msdn.microsoft.com/Forums/vstudio/en-US/ce90eb80-3faf-4266-b6e3-0082191793f7/creation-of-graphics-object-in-wpf -user-control? forum = wpf )

Here's a terribly compressed call to Graphics.MeasureString() . (please enter the code more responsibly)

 SizeF sf = System.Drawing.Graphics.FromHwnd(new System.Windows.Interop.WindowInteropHelper(this).Handle).MeasureString("w", new Font(TheControl.FontFamily.ToString(), (float)TheControl.FontSize)); 
0
source

All Articles