2
我使用以下代碼獲取通用GDI錯誤。通常它遵守並執行得很好,但有時會出現通用GDI +錯誤。有沒有辦法解決這個問題,或者是一種不使用inter-op截圖的方式?通用GDI +錯誤
Public Function CopyImageFromScreen(region as Int32Rect) As BitmapSource
Dim img As New System.Drawing.Bitmap(region.Width, region.Height)
Dim gfx As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(img)
gfx.CopyFromScreen(region.X, region.Y, 0, 0, New System.Drawing.Size(region.Width, region.Height))
img.LockBits(New System.Drawing.Rectangle(0, 0, img.Width, img.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, img.PixelFormat)
Dim hObject As IntPtr = img.GetHbitmap 'This Line Causes the Error
Dim WpfImage As BitmapSource = Interop.Imaging.CreateBitmapSourceFromHBitmap(hObject, IntPtr.Zero, _
System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions())
Return WpfImage
End Function
我查了一下,代碼確實泄漏了內存,現在已經修復了。 CreateBitmapSourceFromHBitmap仍然會定期失敗。我實現了Try/Catch塊,因此它按照你的建議優雅地失敗。謝謝您的幫助。 – PeterM 2011-04-30 04:40:39
@PeterM如果只重試CreateBitmap操作,它會成功還是必須重新運行整個例程? – 2011-04-30 18:05:47