2016-04-25 43 views
-1
int countimages = 0; 
     private void timer1_Tick(object sender, EventArgs e) 
     {   
      Image img = sc.CaptureWindowToMemory(windowHandle); 
      Bitmap bmp = new Bitmap(img,img.Width,img.Height); 
      bmp.Save(@"e:\screenshotsofpicturebox1\screenshot" + countimages + ".bmp"); 
      bmp.Dispose(); 

      string[] images = Directory.GetFiles(@"e:\screenshotsofpicturebox1\", "*.bmp"); 
      if (images.Length > 0) 
      { 
       if (pictureBox1.Image != null) 
       { 
        File.Delete(images[0]); 
        countimages = 0; 
        pictureBox1.Image.Dispose(); 
       } 
       pictureBox1.Image = Image.FromFile(images[countimages]); 
      } 
      countimages += 1; 
      label1.Text = countimages.ToString(); 
     } 
  1. 我要像
  2. 負荷將圖像保存到硬盤上的pictureBox1
  3. 加載到pictureBox1圖像後從硬盤
  4. 刪除文件的新圖像保存到硬盤並將其加載到pictureBox1
  5. 每次刪除文件等等都會有一張新圖片。

的問題,現在是我得到就行了異常:因爲它正在被另一個進程使用如何加載圖像形式目錄到圖片框刪除圖片文件加載到圖片框後,再次下一張圖片?

File.Delete(images[0]); 

該進程無法訪問該文件e:\screenshotsofpicturebox1\screenshot0.bmp

我看到現在它的每次保存新文件到硬盤

screenshot0.bmp 
screenshot1.bmp 

但我婉是每次screenshot0.bmp只有一個文件,只是每次都用新圖像替換它的另一個問題。

+1

以及圖片是在圖片框中開放是很有意義的,你無法將其刪除的權利..?同樣的原因,如果您在照片查看器中打開圖片然後嘗試刪除圖片,則會收到一條關於無法刪除的錯誤消息,因爲它在另一個進程中打開。 – Jacobr365

+0

爲什麼你甚至想要保存並從硬盤上刪除它,當你可以簡單地將它們全部避免並將它顯示在圖片框中? –

回答

0

讀取您的代碼我假設您試圖在每個刻度事件的圖片框中顯示屏幕。 所以,如果這是你的目標,你並不需要保存/刪除它,只需指定圖像對象這樣的PictureBox的Image屬性:

private void timer1_Tick(object sender, EventArgs e) { 
    Image refToDispose = pictureBox1.Image; 
    pictureBox1.Image = sc.CaptureWindowToMemory(windowHandle); 
    refToDispose.Dispose(); 
} 

如果你想保存/反正刪除它,您無法將直接加載的位圖從文件傳遞到PictureBox,因爲它將在使用時鎖定文件。

相反,您可以從另一個具有圖像大小的Bitmap實例創建一個圖形對象並繪製它,因此新的位圖將是沒有可分配給PictureBox的文件鎖定的副本。

在你的代碼更改此:

pictureBox1.Image = Image.FromFile(images[countimages]); 

要這樣:

using (Image imgFromFile = Image.FromFile(images[countimages])) { 
    Bitmap bmp = new Bitmap(imgFromFile.Width, imgFromFile.Height); 
    using (Graphics g = Graphics.FromImage(bmp)) { 
     g.DrawImage(imgFromFile, new Point(0, 0)); 
    } 
    pictureBox1.Image = bmp; 
}