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;

しかし、それを 2 回実行すると、同じファイルに書き込んでいる場合、ファイルが使用中であると表示されます。何か案は?

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 に答える