我一直在制作一个应用程序来拍摄网站快照。 一切正常,直到现在: 我让应用程序拍摄了很多照片,拍摄过程如下:
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 代码的变体。采用 ILSpy)。
错误发生在IntPtr hdc = graphics.GetHdc();行。
使用GetHdc方法时找人问这个“Parameter is Invalid”,人家说可能是因为没有释放之前的GDI对象。事实并非如此,因为 Graphics 对象带有 using 语句,位图也是如此......
我需要注意我同时有很多网络浏览器(我从不销毁它们,我重新使用它们,这是我遇到的另一个错误,这是我解决它的唯一方法......)
当我在 TaskManager 上查看 GDI 对象的数量时,我发现这是一个巨大的数量。但是 - 当我碰巧拥有最多的 GDI 对象时,错误并没有发生...... 我猜这些对象来自 WebBrowsers...?
来自 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,但它工作得很好,直到它抛出此异常的某个阶段。
最佳答案
即使这篇文章很老我也想帮助解决这个问题,因为我有同样的问题并且我是这样解决的:
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() 一次。之后我再也不用调用 graphics.GetHdc()。
关于c# - 使用 Graphics.GetHdc 时参数无效异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8460109/