我已經被要求調試一些代碼,試圖通過將屏幕截圖保存到BMP來嘗試在VB.Net中創建圖形的電影。我發現它擊中萬個GDI對象的限制後,它是失敗的,並確定泄漏是從這個代碼:GDI對象沒有刪除
Dim r As Integer
Dim hdcdest As System.IntPtr = CType(CreateCompatibleDC(CInt(GetWindowDC(frmDynamicsMDI.MainControl.fraAnimation.Handle))), IntPtr)
Dim hdcbitmap As System.IntPtr = CType(CreateCompatibleBitmap(GetWindowDC(frmDynamicsMDI.MainControl.fraAnimation.Handle), _
frmDynamicsMDI.MainControl.fraAnimation.Size.Width - (0 + CropRight), _
frmDynamicsMDI.MainControl.fraAnimation.Size.Height - (10 + 0)), IntPtr)
SelectObject(hdcdest, CInt(hdcbitmap))
BitBlt(hdcdest, 0, 0, frmDynamicsMDI.MainControl.fraAnimation.Width - (0 + CropRight), frmDynamicsMDI.MainControl.fraAnimation.Height - (10 + 0), _
GetWindowDC(frmDynamicsMDI.MainControl.fraAnimation.Handle), 0, 10, 13369376)
Image = System.Drawing.Image.FromHbitmap(hdcbitmap)
r = DeleteDC(CInt(GetWindowDC(frmDynamicsMDI.MainControl.fraAnimation.Handle)))
DeleteObject(CInt(hdcdest))
DeleteObject(CInt(hdcbitmap))
而且BitBlt的聲明爲:
Private Declare Function BitBlt Lib "GDI32" (ByVal hdestDC As IntPtr, ByVal x As Integer, ByVal y As Integer, _
ByVal nwidth As Integer, ByVal nheight As Integer, ByVal HsrcDC As IntPtr, ByVal xsrc As Integer, ByVal ysrc As Integer, ByVal _
dwRop As Int32) As Boolean
的2個System.IntPtr
建立呼叫創建2個GDI對象,'BitBlt'創建1個。我發現的問題是DeleteObject()
調用每個都只移除1個GDI對象。
那麼刪除調用是不正確的?或者是否有其他對象與GDI對象一起浮動,這些對象不會被刪除?
您的pinvoke聲明不好,從pinvoke.net網站上獲得更好的聲明。有很多泄漏,其中一個是由您的SelectObject()調用引起的。您必須存儲其返回值並在銷燬設備上下文之前再次調用SelectObject()以恢復原始選擇。你也忘記摧毀GetWindowDC()返回值。 –