2013-04-12 45 views
0

我正在編寫一個需要截屏的應用程序,但隨機它會拋出一個GDI +一般錯誤。不幸的是,一個通用的錯誤並不能幫助我很好的調試。我對屏幕捕獲代碼: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; 

但是,如果您運行兩次它說,文件正在使用,如果你正在寫同一個文件。有任何想法嗎?

+0

你SO搜索 「通用GDI +錯誤」?你會感到驚訝... –

+0

@ThorstenDittmar我搜索了StackOverflow,但我找不到有類似的方法調用。也許我沒有足夠努力,然後我道歉。 – Thegluestickman

回答

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); 
} 
+0

它說「bmpScreenShot在當前上下文中不存在」 位圖bmpScreenshot2 =新的位圖(bmpScreenShot); – Thegluestickman

+0

我假設你可以自己解決這個問題......我會修復我的代碼。 –

+0

哎呀,我什至沒有注意到:P感謝你的幫助! – Thegluestickman

相關問題