public static class ScreenCapture
{
///
/// 擷取螢幕指定矩形區域並儲存為 BMP
///
/// 來源左上角螢幕座標
/// 目的地圖片左上角座標 (通常 0,0)
/// 擷取寬高
/// 輸出檔案路徑
public static void Capture(Point sourcePoint, Point destPoint, Rectangle region, string filePath)
{
using (Bitmap bmp = new Bitmap(region.Width, region.Height))
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(sourcePoint, destPoint, region.Size);
}
bmp.Save(filePath, ImageFormat.Bmp);
}
}
private void btnCapture_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
// 取得控件在螢幕上的絕對座標
Point screenLoc = this.PointToScreen(Point.Empty);
// 或針對特定控件:axMapControl1.PointToScreen(Point.Empty)
ScreenCapture.Capture(screenLoc, Point.Empty,
new Rectangle(this.Location, this.Size), saveFileDialog1.FileName);
}
CopyFromScreen 直接從顯示裝置上下文 (DC) 複製像素,效能極佳,無需 P/Invoke BitBlt。PointToScreen(Point.Empty) 將控件用戶座標轉螢幕座標。using 確保 Bitmap/Graphics 即時釋放非託管資源。public static Bitmap CaptureAllScreens()
{
Rectangle bounds = Rectangle.Empty;
foreach (Screen s in Screen.AllScreens)
bounds = Rectangle.Union(bounds, s.Bounds);
Bitmap bmp = new Bitmap(bounds.Width, bounds.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
foreach (Screen s in Screen.AllScreens)
g.CopyFromScreen(s.Bounds.Location, s.Bounds.Location, s.Bounds.Size);
}
return bmp;
}
Graphics.CopyFromScreen 是 .NET 截圖的標準高效 API,配合 PointToScreen 即可精準擷取任意控件或區域,程式碼簡潔且無外部依賴。