简体   繁体   English

通用 GDI+ 错误

[英]Generic GDI+ Error

I get as Generic GDI Error with the following code.我得到以下代码的通用 GDI 错误。 Usually it complies and executes just fine but sometimes fails with a Generic GDI+ Error.通常它符合并执行得很好,但有时会因通用 GDI+ 错误而失败。 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

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.即使这没有帮助,最好的做法也是清理一次性对象并且不依赖 GC。

That said, "classic" image support (ie System.Drawing.Image) in the .NET framework is mostly a wrapper over the native GDI/GDI+ libraries and are prone to leaking unmanaged resources.也就是说,.NET 框架中的“经典”图像支持(即 System.Drawing.Image)主要是对原生 GDI/GDI+ 库的封装,并且容易泄漏非托管资源。

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.我的建议是将imggfx对象包装在using块中,并通过对DeleteObject的互操作调用显式删除hObject句柄,并包含在 try/finally 块中,以防CreateBitmapSourceFromHBitmap失败。

...why the framework provides a GetHbitmap method on the Image class, but not a way to delete it without interop code is a mystery. ...为什么框架在图像 class 上提供了 GetHbitmap 方法,但在没有互操作代码的情况下无法删除它是一个谜。 Check out the MSDN docs on GetHbitmap for more details on that.查看 GetHbitmap 上的 MSDN 文档以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM