The FromImage, FromHdc, and FromHwnd Methods in GDI+


This article has been excerpted from book "Graphics Programming with GDI+".

An application can use Graphics class members to get a Graphics object. The Graphics class provides three methods to create a Graphics object: FromHwnd, FromHdc, and FromImage.

FromImage takes and Image object as input parameter and returns a Graphics object. The following code snippet creates a Graphics object from an Image object. One a Graphics object has been created, you can call its members.


        Image img = Image.FromFile("Rose.jpg");
        Graphics g = Graphics.FromImage (img);

        // Do something
        g.Dispose();


Note: Make sure you call the Dispose method of the Graphics object when you're finished with it.

FromHdc creates a Graphics object from a window handle to a device context. The following code snippet shows an example in which FromHdc takes one parameter, of type IntPtr.


        IntPtr hdc = e.Graphics.GetHdc();
        Graphics g = Graphics.FromHdc (hdc);

        // Do something
        e.Graphics.ReleaseHdc (hdc);
        g.Dispose();


Note: You need to call the ReleaseHdc method to release resource allocated by a window handle to a device context, and also make sure you call the Dispose method of the Graphics object when you're finished with it.

FromHwnd returns a Graphics object for a form. The following method takes a window handle.

        Graphics g = Graphics.FromHwnd(this.Handle);


To draw on a form, an application can pass this handle. One an application has a Graphics object, it can call any Graphics class method to draw graphics object.

Conclusion

Hope the article would have helped you in understanding The FromImage, FromHdc, and FromHwnd Methods in GDI+. Read other articles on GDI+ on the website.


bookGDI.jpg This book teaches .NET developers how to work with GDI+ as they develop applications that include graphics, or that interact with monitors or printers. It begins by explaining the difference between GDI and GDI+, and covering the basic concepts of graphics programming in Windows.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.