Graphics.FromHwnd(IntPtr) 方法

定义

从窗口的指定句柄创建新的 Graphics

public:
 static System::Drawing::Graphics ^ FromHwnd(IntPtr hwnd);
public static System.Drawing.Graphics FromHwnd (IntPtr hwnd);
static member FromHwnd : nativeint -> System.Drawing.Graphics
Public Shared Function FromHwnd (hwnd As IntPtr) As Graphics

参数

hwnd
IntPtr

nativeint

窗口的句柄。

返回

此方法为指定的窗口句柄返回新的 Graphics

示例

下面的代码示例设计为与 Windows 窗体 一起使用,它需要 PaintEventArgse(事件处理程序的参数Paint)和 thisFormForm本示例的 ) 。 此代码执行以下操作:

  • 创建一个新的内部指针变量 hwnd ,并将其设置为示例窗体的句柄。

  • 从句柄创建新的 Graphics

  • 使用红色笔将矩形绘制到新的 Graphics

  • 释放新的 Graphics

public:
   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( gcnew Pen( Color::Red,3.0f ), 0, 0, 200, 100 );

      // Dispose of new graphics.
      delete newGraphics;
   }
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();
}
Private Sub FromHwndHwnd(ByVal e As PaintEventArgs)

    ' Get handle to form.
    Dim hwnd As IntPtr = Me.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

注解

应始终调用 Dispose 方法来释放 GraphicsFromHwnd 方法创建的 和相关资源。

适用于