Graphics.FromHwnd(IntPtr) Method

Definition

Creates a new Graphics from the specified handle to a window.

C#
public static System.Drawing.Graphics FromHwnd(IntPtr hwnd);

Parameters

hwnd
IntPtr

Handle to a window.

Returns

This method returns a new Graphics for the specified window handle.

Examples

The following code example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler, as well as thisForm, the Form for the example. The code performs the following actions:

  • Creates a new internal pointer variable hwnd and sets it to the handle of the example's form.

  • Creates a new Graphics from the handle.

  • Draws a rectangle to the new Graphics using a red pen.

  • Disposes the new Graphics.

C#
private void FromHwndHwnd(PaintEventArgs e)
{

    // Get handle to form.
    IntPtr hwnd = this.Handle;

    // Create new graphics object using handle to window.
    Graphics newGraphics = Graphics.FromHwnd(hwnd);

    // Draw rectangle to screen.
    newGraphics.DrawRectangle(new Pen(Color.Red, 3), 0, 0, 200, 100);

    // Dispose of new graphics.
    newGraphics.Dispose();
}

Remarks

You should always call the Dispose method to release the Graphics and related resources created by the FromHwnd method.

Applies to

Product Versions
.NET 8 (package-provided), 9 (package-provided)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7 (package-provided), 4.7, 4.7.1 (package-provided), 4.7.1, 4.7.2 (package-provided), 4.7.2, 4.8 (package-provided), 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9