本文提供一個完整的 C# Windows Forms 專案,實作類似 QQ 的螢幕截圖功能,包含全螢幕截取、滑鼠框選區域截取、圖片預覽、儲存等核心功能。專案包含兩個主要表單類別:CaptureScreenForm(主視窗)與 MouseCaptureForm(區域選取視窗)。
主視窗負責 UI 佈局與全螢幕截圖邏輯,包含工具列按鈕(全螢幕截取、滑鼠截取、清除、儲存、關於、退出)與一個 PictureBox 用於顯示截圖預覽。
public class CaptureScreenForm : Form
{
private PictureBox picbox;
private Button fullScreenBtn, mouseCaptureBtn, ClearBtn, saveBtn, aboutBtn, exitBtn;
private Panel panel1;
public static Image image = null;
// ... 元件初始化與事件繫結
}
透過 GDI BitBlt API 直接從螢幕裝置內容複製像素資料到位圖,效能優於 Graphics.CopyFromScreen。
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest,
int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
public static Bitmap WindowFullScreen()
{
Graphics grpScreen = Graphics.FromHwnd(IntPtr.Zero);
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height, grpScreen);
Graphics grpBitmap = Graphics.FromImage(bitmap);
IntPtr hdcScreen = grpScreen.GetHdc();
IntPtr hdcBitmap = grpBitmap.GetHdc();
BitBlt(hdcBitmap, 0, 0, bitmap.Width, bitmap.Height,
hdcScreen, 0, 0, 0x00CC0020); // SRCCOPY
grpBitmap.ReleaseHdc(hdcBitmap);
grpScreen.ReleaseHdc(hdcScreen);
grpBitmap.Dispose();
grpScreen.Dispose();
return bitmap;
}
建立全螢幕無邊框視窗,背景為全螢幕截圖,支援滑鼠拖曳選取矩形區域、八個控制點調整大小、雙擊確認截圖、右鍵/ESC 取消等互動。
public class MouseCaptureForm : Form
{
private Point pot;
private Rectangle area = Rectangle.Empty;
private Image img;
private int index = -1; // 控制點索引
private Label tiptext; // 操作提示
public MouseCaptureForm()
{
this.Bounds = Screen.PrimaryScreen.Bounds;
this.BackgroundImage = CaptureScreenForm.WindowFullScreen();
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.WindowState = FormWindowState.Maximized;
InitializeComponent();
}
// ... 滑鼠事件處理:OnMouseDown, OnMouseMove, OnMouseUp, OnPaint
}
GetHandleRect 計算八個調整點矩形,GetSelectedHandle 判斷滑鼠位置對應哪個控制點。Bitmap.Clone 丟擲「記憶體不足」例外。finally 區塊或 Dispose 中正確釋放。CaptureScreen/
├── CaptureScreenForm.cs // 主視窗、全螢幕截圖、儲存邏輯
└── MouseCaptureForm.cs // 區域選取視窗、滑鼠互動、區域截圖
啟動後顯示主視窗工具列,點選「全螢幕截取」即刻捕捉桌面並顯示於預覽區;點選「滑鼠截取」進入全螢幕選取模式,拖曳框選區域後雙擊完成,自動回填主視窗預覽。
Screen.AllScreens 支援跨螢幕截取原始碼作者:Star (2006-03-17),整理優化由 AI 協助完成。