通用GDI +错误

Pet*_*erM 2 .net vb.net wpf gdi+

我使用以下代码获得通用GDI错误.通常它符合并执行得很好但有时会因Generic GDI + Error而失败.有没有办法解决这个问题,或者是一种不使用inter-op拍摄截图的方法?

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
Run Code Online (Sandbox Code Playgroud)

Kev*_*lin 5

这可能会有所帮助,也可能没有帮助,但我可以告诉您,这不会清理此方法中分配的任何资源.即使这没有帮助,最好的做法是将清洁一次性物品并且不依赖于GC.

也就是说,.NET框架中的"经典"图像支持(即System.Drawing.Image)主要是本机GDI/GDI +库的包装器,并且容易泄漏非托管资源.

我建议将块imggfx对象包装在一个using块中,并hObject通过对DeleteObject的interop调用显式删除句柄,如果CreateBitmapSourceFromHBitmap失败则包含在try/finally块中.

...为什么框架在Image类上提供GetHbitmap方法,但没有一种方法可以在没有interop代码的情况下删除它是一个谜.有关详细信息,请查看GetHbitmap上的MSDN文档.