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