Invalid Exception parameter when using Graphics.GetHdc

I am making an application to take snapshots of websites. Everything works well, so far: My application accepts LOTS of photos, and the process of shooting the image is as follows:

using (Graphics graphics = Graphics.FromImage(mBitmap))
{
   IntPtr hdc = graphics.GetHdc();
   SendMessage(new HandleRef(mWebBrowser, mWebBrowser.Handle), 791, hdc, (IntPtr)30);
   BitBlt(new HandleRef(graphics, hdc), 0, 0, mBitmap.Width, mBitmap.Height, new HandleRef(graphics, hdc), 0, 0, 13369376);
   graphics.ReleaseHdc();
}

(this is a change to the DrawToBitmap code from the WebBrowser control, taken with ILSpy).

The error occurs on IntPtr hdc = graphics.GetHdc (); line.

I searched for people asking about this "Parameter is invalid" when using the GetHdc method, and people said that this could be because GDI objects have not been released before. this is not so, since the Graphics object has a using statement, as well as a bitmap ...

I need to note that I have many web browsers at the same time (I never destroy them, I reuse them, this is for another error that I had, and this was the only way to solve it ...)

When I look at the TaskManager for the number of GDI objects, I see that this is a huge amount. But - the error did not occur when I had more GDI objects ... I assume that this number of objects comes from WebBrowsers ...?

Download source package DrawToBitmap from ILSpy:

int nWidth = Math.Min(this.Width, targetBounds.Width);
int nHeight = Math.Min(this.Height, targetBounds.Height);
Bitmap image = new Bitmap(nWidth, nHeight, bitmap.PixelFormat);
using (Graphics graphics = Graphics.FromImage(image))
{
    IntPtr hdc = graphics.GetHdc();
    UnsafeNativeMethods.SendMessage(new HandleRef(this, this.Handle), 791, hdc, (IntPtr)30);
    using (Graphics graphics2 = Graphics.FromImage(bitmap))
    {
        IntPtr hdc2 = graphics2.GetHdc();
        SafeNativeMethods.BitBlt(new HandleRef(graphics2, hdc2), targetBounds.X, targetBounds.Y, nWidth, nHeight, new HandleRef(graphics, hdc), 0, 0, 13369376);
        graphics2.ReleaseHdcInternal(hdc2);
    }
    graphics.ReleaseHdcInternal(hdc);
}

The documentation claims that Webbrowser does not support DrawToBitmap, but it works fine to some extent when it just throws this exception.

+5
source share
1 answer

, , , :

private static Graphics graphics = null;
private static IntPtr hdc = IntPtr.Zero;
private static IntPtr dstHdc = IntPtr.Zero;

private static Capture()
{
    if (graphics == null)
    {
       hdc = GetDC(IntPtr.Zero);
       graphics = Graphics.FromImage(bitmap);
       dstHdc = graphics.GetHdc();
    }
    BitBlt(dstHdc, 0, 0, screen_resolution.Width, screen_resolution.Height, hdc, 0, 0, RasterOperation.SRC_COPY);
}

, graphics.GetHdc() , Zero. call graphics.GetHdc().

+1

All Articles