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
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
andgfx
objects in ausing
block, as well as explicitly deleting thehObject
handle with an interop call to DeleteObject, enclosed in a try/finally block in caseCreateBitmapSourceFromHBitmap
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.