简体   繁体   中英

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

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.

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) eg

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.

None of the preceding answers worked for me. I found Rajnikant Rajwadi solution effective (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 is a horribly condensed call to Graphics.MeasureString() . (please 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));

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

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

What you can do: load another (simple) form, with just a picture, and hide it when your main form is loaded.

Since your Load event will probably run on the UI thread. Call DoEvents to make the other form appear.

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