Generic GDI+ Error

大憨熊 提交于 2019-12-11 01:38:16

问题


I get as Generic GDI Error with the following code. Usually it complies and executes just fine but sometimes fails with a Generic GDI+ Error. Is there some way to solve the issue, or a way to take a screenshot without using 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

回答1:


This may or may not help, but near as I can tell you are not cleaning up any of the resources allocated in this method. Even if this doesn't help, it's best practice and proper to clean up disposable objects and to not rely on the GC.

That said, "classic" image support (i.e. System.Drawing.Image) in the .NET framework is mostly a wrapper over the native GDI/GDI+ libraries and are prone to leaking unmanaged resources.

What I suggest is wrapping the img and gfx objects in a using block, as well as explicitly deleting the hObject handle with an interop call to DeleteObject, enclosed in a try/finally block in case CreateBitmapSourceFromHBitmap fails.

...why the framework provides a GetHbitmap method on the Image class, but not a way to delete it without interop code is a mystery. Check out the MSDN docs on GetHbitmap for more details on that.



来源:https://stackoverflow.com/questions/5826644/generic-gdi-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!