2010-03-31 52 views
3

我試圖創建一個WinForms應用程序,它在設定的時間間隔內進行屏幕截圖。我認爲我的代碼是正確的,但是當我嘗試運行它時,出現錯誤消息「System.Runtime.InteropServices.ExternalException未處理,GDI +中發生了一個通用錯誤。」C# - 以計時器爲基礎的屏幕截圖

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer(); 
    Thread th; 
    private static Bitmap bmpScreenshot; 
    private static Graphics gfxScreenshot; 

    void TakeScreenShot() 
    { 
     bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); 
     gfxScreenshot = Graphics.FromImage(bmpScreenshot); 
     gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); 
     bmpScreenshot.Save(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures", ImageFormat.Png); 
     th.Abort(); 
    } 

    void StartThread(object sender, EventArgs e) 
    { 
     th = new Thread(new ThreadStart(TakeScreenShot)); 
     th.Start(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures"); 
     t.Interval = 500; 
     t.Tick += new EventHandler(StartThread); 
     t.Start(); 
    } 

多數民衆贊成讓我煩惱該生產線是:

bmpScreenshot.Save(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures", ImageFormat.Png); 

正在發生的事情不對任何想法?提前致謝。

回答

3

您需要與實際文件名保存,就像這樣:

bmpScreenshot.Save(Environment.GetFolderPath 
    (Environment.SpecialFolder.DesktopDirectory) 
    + @"\ScreenCaptures\newfile.png", ImageFormat.Png); 

你的代碼是通過在不包括文件名的路徑。另外,請檢查以確保Environment.GetFolderPath(...)返回的路徑末尾沒有「\」,否則最終會在路徑中顯示「\\」。

+0

這很奇怪 - 我必須鍵入3反斜槓才能讓2出現。 – MusiGenesis 2010-03-31 00:40:57