参数在使用Graphics.GetHdc时为无效异常

本文关键字:无效 异常 GetHdc Graphics 参数 | 更新日期: 2023-09-27 18:17:41

我一直在做一个网站快照的应用程序。一切都很顺利,直到现在:我让应用程序拍摄了许多照片,图像拍摄的过程如下:

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();
}

(这是来自WebBrowser控件的DrawToBitmap的代码的变化。

在IntPtr上发生错误hdc = graphics.GetHdc();线。

我在使用GetHdc方法时询问了有关"Parameter is Invalid"的问题,人们说这可能是因为没有释放先前的GDI对象。但事实并非如此,因为Graphics对象在using语句中,位图也在using语句中…

我需要注意的是,我有许多浏览器在同一时间(我从不破坏他们,我重用他们,这是另一个错误,我有,这是唯一的方法,我可以解决它…)

当我在TaskManager上查看GDI对象的数量时,我看到它是一个巨大的数量。但是-当我碰巧有最多的GDI对象时,错误没有发生…我猜这个数量的对象来自于web浏览器…?

来自ILSpy的原始DrawToBitmap代码是:

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);
}

文档声称Webbrowser不支持DrawToBitmap,但它工作得很好,直到某个阶段,当它只是抛出这个异常。

参数在使用Graphics.GetHdc时为无效异常

即使这篇文章很老了,我也想帮助解决这个问题,因为我有同样的问题,我是这样解决的:

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);
}

我的解决方案是,当对象为0时,我只调用graphics.GetHdc()一次。在那之后,我再也不用call graphics.GetHdc()了。