0

我正在编写一个拍摄屏幕截图的应用程序,但它会随机抛出 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;

但是,如果您运行两次,则表示该文件正在使用中,如果您正在写入同一个文件。有任何想法吗?

4

1 回答 1

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);
}
于 2013-04-12T12:28:18.280 回答