C# 結合 VB 快速開發與 C++ 高效能,基於 .NET Framework 提供強大圖形/網路程式能力。GDI+ 為 GDI 演進版,封裝繁雜細節,但仍可透過 P/Invoke 呼叫 GDI 底層功能 (如 BitBlt) 實現高效螢幕截圖。
using System.Runtime.InteropServices;
[DllImport("gdi32.dll")]
private static extern bool BitBlt(
IntPtr hdcDest, // 目標裝置內容 (DC) 控制碼
int nXDest, // 目標矩形左上角 X
int nYDest, // 目標矩形左上角 Y
int nWidth, // 寬度
int nHeight, // 高度
IntPtr hdcSrc, // 來源 DC 控制碼
int nXSrc, // 來源矩形左上角 X
int nYSrc, // 來源矩形左上角 Y
int dwRop // 光柵操作代碼 (SRCCOPY = 0x00CC0020)
);
IntPtr hdc = graphics.GetHdc(); (對應 Graphics 物件)。graphics.ReleaseHdc(hdc); (必須成對呼叫,否則資源洩漏)。IntPtr screenDc = GetDC(IntPtr.Zero); (需 DllImport("user32.dll") 宣告 GetDC/ReleaseDC)。Bitmap。Bitmap 建立 Graphics,取得目標 DC (hdcDest)。hdcSrc)。BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY) 將螢幕像素複製至 Bitmap。Bitmap 為 JPEG/PNG。private const int SRCCOPY = 0x00CC0020; // 直接複製像素 // 其他常見:CAPTUREBLT = 0x40000000 (包含分層視窗)
下一節將展示完整 WinForms 專案佈局、控件配置與按鈕點擊事件中的完整截圖程式碼。