2012-06-01 99 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處理本地設備上下文太

相關問題