2011-03-19 97 views
0

我想僅捕獲應用程序的預定義區域,例如我想僅打印屏幕組框。我將this.bounds更改爲groupbox.bounds,但它不起作用。它捕獲其他區域,但不包含組框。有任何想法嗎? 的代碼是:C#打印屏幕預定義區域

// 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) 
{enter code here 
    // Save the screenshot to the specified path that the user has chosen 
    bmpScreenshot.Save(saveImageDialog.FileName, ImageFormat.Png); 
} 

感謝。

+0

出了什麼問題'DrawToBitmap'?這和[你最後一個問題]有什麼不同(http://stackoverflow.com/questions/5336553/c-print-screen-active-window)? – 2011-03-19 11:10:45

+0

@Code Grey:請在這個問題上看到我對答案的評論。 – 2011-03-19 11:37:50

回答

2

問題是Bounds屬性中的座標是相對於其父項,但CopyFromScreen需要絕對座標。

嘗試使用PointToScreen方法:

Point p = this.PointToScreen(new Point(groupBox.Bounds.X, groupBox.Bounds.Y)); 
gfxScreenshot.CopyFromScreen(p.X, p.Y, 0, 0, 
       groupBox.Bounds.Size, CopyPixelOperation.SourceCopy); 
+0

謝謝!但是,第一行必須更改爲: Point p = this.PointToScreen(new Point(groupBox2.Bounds.X,groupBox2.Bounds.Y)); 爲了正常工作。無論如何非常感謝你! – cnewbie 2011-03-19 13:47:02

+0

@cnewbie:你說得對,我修好了 – 2011-03-19 14:16:08