2012-06-01 64 views
2

在Windows窗体的背面,我得到一个窗口DC,用Graphics.FromHdc创建一个Graphics对象,然后在释放DC之前将图形对象置于之前。在Graphics.Dispose之前或之后释放DC?

Private Declare Function GetWindowDC Lib "user32.dll" (ByVal hwnd As IntPtr) As IntPtr 
Private Declare Function ReleaseDC Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal hdc As IntPtr) As Integer 

Dim hdc As IntPtr = GetWindowDC(Me.Handle) 

Try 
    Using g As Graphics = Graphics.FromHdc(hdc) 
     ' ... use g ... 
    End Using 
Finally 
    ReleaseDC(Me.Handle, hdc) 
End Try 

有关Graphics.FromHdc的Microsoft文档显示了类似的代码。 (它使用Graphics.GetHdcGraphics.ReleaseHdc,而不是Win32的GetWindowDcReleaseDC)。然而,它们释放的DC 处置的图形对象之前:

' Get handle to device context. 
Dim hdc As IntPtr = e.Graphics.GetHdc() 

' Create new graphics object using handle to device context. 
Dim newGraphics As Graphics = Graphics.FromHdc(hdc) 

' Draw rectangle to screen. 
newGraphics.DrawRectangle(New Pen(Color.Red, 3), 0, 0, 200, 100) 

' Release handle to device context and dispose of the Graphics ' object 
e.Graphics.ReleaseHdc(hdc) 
newGraphics.Dispose() 

他们为什么这样做这种方式? DC应该在Graphics.Dispose之前还是之后发布? 错误的顺序可能导致资源泄漏或内存损坏?

回答

1

从Graphics.Dispose方法:

private void Dispose(bool disposing) 
{ 
..SNIP... 
    if (this.nativeGraphics != IntPtr.Zero) 
    { 
     try 
     { 
      if (this.nativeHdc != IntPtr.Zero) <<--- 
      { 
       this.ReleaseHdc(); <<--- 
    } 

所以看起来它会自行TBH释放HDC。

[编辑]

它实际上是:

[DllImport("gdiplus.dll", CharSet = CharSet.Unicode, EntryPoint = "GdipReleaseDC",  ExactSpelling = true, SetLastError = true)] 
private static extern int IntGdipReleaseDC(HandleRef graphics, HandleRef hdc); 

,这是获得所谓的,不知道是否gdiplus释放DC处理本地设备上下文太

相关问题