C#中的“无法引用system.drawing.dll”

时间:2017-08-19 08:53:59

标签: c#

当我创建连续执行该功能的代码时,它会正常工作4分钟,但会出现错误:

  

无法引用system.drawing.dll

并且无法执行。

我已经尝试过几次搜索网络来解决它,但我没有和你有过相同的经历。尝试编写Google翻译并提出问题。

public static Bitmap GetScreenshot(IntPtr hwnd)
{
    RECT rc;
    GetWindowRect(new HandleRef(null, hwnd), out rc);

    Bitmap bmp = new Bitmap(rc.Right - rc.Left, rc.Bottom - rc.Top, PixelFormat.Format32bppArgb);
    Graphics gfxBmp = Graphics.FromImage(bmp);
    IntPtr hdcBitmap;

    try
    {
        hdcBitmap = gfxBmp.GetHdc();
    }
    catch
    {
        return null;
    }

    bool succeeded = PrintWindow(hwnd, hdcBitmap, 0x3);
    gfxBmp.ReleaseHdc(hdcBitmap);

    if (!succeeded)
    {
        gfxBmp.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(Point.Empty, bmp.Size));
    }

    IntPtr hRgn = CreateRectRgn(0, 0, 0, 0);
    GetWindowRgn(hwnd, hRgn);

    Region region = Region.FromHrgn(hRgn);//err here once

    if (!region.IsEmpty(gfxBmp))
    {
        gfxBmp.ExcludeClip(region);
        gfxBmp.Clear(Color.Transparent);
    }

    gfxBmp.Dispose();
    return bmp;
}

Timer timer3 = new System.Windows.Forms.Timer();
timer3.Interval = 1; // 1초
timer3.Tick += new EventHandler(timer_Tick2);
timer3.Start();

2 个答案:

答案 0 :(得分:1)

我想你可能有内存泄漏。仔细观察,我注意到的事情是Region对象没有被处理掉:

Region region = Region.FromHrgn(hRgn);//err here once
if (!region.IsEmpty(gfxBmp))
{
    gfxBmp.ExcludeClip(region);
    gfxBmp.Clear(Color.Transparent);
}
gfxBmp.Dispose();
region.Dispose();  //Try adding this in.
return bmp;

答案 1 :(得分:-1)

        IntPtr hRgn = NativeMethod.CreateRectRgn(0, 0, 0, 0);

        NativeMethod.GetWindowRgn(hwnd, hRgn);

        using (var region = Region.FromHrgn(hRgn))
        {
            if (!region.IsEmpty(gfxBmp))
            {
                gfxBmp.ExcludeClip(region);
                gfxBmp.Clear(Color.Transparent);
            }
        }

        gfxBmp.Dispose();

        NativeMethod.DeleteObject(hRgn);

这是我的代码...

可能是因为 GDI 处理内存泄漏。