This documentation is archived and is not being maintained.

Graphics.FromHwnd Method

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

[Visual Basic]
Public Shared Function FromHwnd( _
   ByVal hwnd As IntPtr _
) As Graphics
[C#]
public static Graphics FromHwnd(
 IntPtr hwnd
);
[C++]
public: static Graphics* FromHwnd(
 IntPtr hwnd
);
[JScript]
public static function FromHwnd(
   hwnd : IntPtr
) : Graphics;

Parameters

hwnd
Handle to a window.

Return Value

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

Example

[Visual Basic, C#] The following 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 object 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 object from the handle.
  • Draws a rectangle to the new Graphics object using a red pen.
  • Disposes the new Graphics object.
[Visual Basic] 
Public Sub FromHwndHwnd(e As PaintEventArgs)
' Get handle to form.
Dim hwnd As New IntPtr()
hwnd = thisForm.Handle
' Create new graphics object using handle to window.
Dim newGraphics As Graphics = Graphics.FromHwnd(hwnd)
' Draw rectangle to screen.
newGraphics.DrawRectangle(New Pen(Color.Red, 3), 0, 0, 200, 100)
' Dispose of new graphics.
newGraphics.Dispose()
End Sub
        
[C#] 
public void FromHwndHwnd(PaintEventArgs e)
{
// Get handle to form.
IntPtr hwnd = new IntPtr();
hwnd = thisForm.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();
}
        

[C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

Graphics Class | Graphics Members | System.Drawing Namespace

Show: