首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 螢幕截圖實作:Graphics.CopyFromScreen 高效截取指定區域

     編輯:關於C#

核心類別

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);
    }
}

WinForm 呼叫範例

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 即可精準擷取任意控件或區域,程式碼簡潔且無外部依賴。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved