屏幕捕获中出现GDI +中的一般错误

时间:2013-04-12 12:20:07

标签: c# screenshot

我正在编写一个采用屏幕截图的应用程序,但随机它会抛出GDI +泛型错误。不幸的是,一般错误并没有帮助我调试好。我的屏幕截图代码是:

    static void CaptureScreen()
    {
        bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        // Create a graphics object from the bitmap
        gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        // Take the screenshot from the upper left corner to the right bottom corner
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        // Save the screenshot to the specified path that the user has chosen
        bmpScreenshot.Save(savePath + "img" + times.ToString()+ ".png", ImageFormat.Png);
    }

偶尔会给我一个通用错误,所以我想“也许我应该处理位图和图形变量”

    static void CaptureScreen()
    {
        bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        // Create a graphics object from the bitmap
        gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        // Take the screenshot from the upper left corner to the right bottom corner
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
        // Save the screenshot to the specified path that the user has chosen
        bmpScreenshot.Save(savePath + "img" + times.ToString()+ ".png", ImageFormat.Png);

        bmpScreenshot.Dispose();
        gfxScreenshot.Dispose();
    }

然后删除所述文件:

            for (int i = 1; i == times; i++)
            {
                File.Delete(savePath + @"\img" + i.ToString() + ".png");
            }
            times = 0;

但是,如果你运行了两次它表示文件正在使用,如果你正在写同一个文件。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

以下内容可能有所帮助:

using (bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb))
using (gfxScreenshot = Graphics.FromImage(bmpScreenshot))
{
    // Take the screenshot from the upper left corner to the right bottom corner
    gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

    Bitmap bmpScreenshot2 = new Bitmap(bmpScreenshot); // FIX: Change "S" to "s"...
    // Save the screenshot to the specified path that the user has chosen
    bmpScreenshot2.Save(savePath + "img" + times.ToString()+ ".png", ImageFormat.Png);
}