2011-03-17 101 views
2

我目前正在嘗試使用Visual C#打印屏幕活動窗口。我有這樣的代碼:C#打印屏幕活動窗口

SaveFileDialog saveImageDialog = new SaveFileDialog(); 
saveImageDialog.Title = "Select output file:"; 
saveImageDialog.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"; 
//saveImageDialog.FileName = printFileName; 
if (saveImageDialog.ShowDialog() == DialogResult.OK) 
{ 
    // Set the bitmap object to the size of the screen 
    bmpScreenshot = new Bitmap(this.Bounds.Width, this.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(this.Bounds.X, this.Bounds.Y, 0, 0, this.Bounds.Size, CopyPixelOperation.SourceCopy); 
    // Save the screenshot to the specified path that the user has chosen 
    bmpScreenshot.Save(saveImageDialog.FileName, ImageFormat.Png); 
} 

但是,這段代碼也捕獲了SaveImageDialog。任何解決這個問題?非常感謝。

回答

4

最簡單的方法將是切換代碼:

// Set the bitmap object to the size of the screen 
bmpScreenshot = new Bitmap(this.Bounds.Width, this.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(this.Bounds.X, this.Bounds.Y, 0, 0, 
          this.Bounds.Size, CopyPixelOperation.SourceCopy); 

SaveFileDialog saveImageDialog = new SaveFileDialog(); 
saveImageDialog.Title = "Select output file:"; 
saveImageDialog.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"; 
//saveImageDialog.FileName = printFileName; 
if (saveImageDialog.ShowDialog() == DialogResult.OK) 
{ 
    // Save the screenshot to the specified path that the user has chosen 
    bmpScreenshot.Save(saveImageDialog.FileName, ImageFormat.Png); 
} 

首先創建截圖和比顯示保存對話框,並將其保存到光盤,如果對話框用OK關閉。

問題是,在您的代碼中,程序沒有時間重新繪製表單。如果你想保留你的代碼結構,你需要給它一些時間來處理未決事件,可能通過調用Application.DoEvents

+0

啊,爲什麼我沒有想到它呢?它是如此容易。非常感謝! – cnewbie 2011-03-19 04:44:41

+0

另一個問題,如果我可能會問,我想只捕獲應用程序的預定義區域,例如我想只打印屏幕組框。我將this.bounds更改爲groupbox.bounds,但它不起作用。它捕獲其他區域,但不包含組框。有任何想法嗎? – cnewbie 2011-03-19 04:46:12

+0

@cnewbie:這真的是另一個問題,請把它作爲一個:) – 2011-03-19 07:42:20