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 事件处理程序的参数,以及 thisForm示例的 Form。 该代码执行以下操作:

  • 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 方法来释放 FromHwnd 方法创建的 Graphics 和相关资源。

适用于