在 C# 中,若要依滑鼠點擊位置擷取螢幕區域,核心概念是取得螢幕座標,再利用 Graphics.CopyFromScreen 把指定範圍複製到 Bitmap。
可透過 Cursor.Position 取得目前滑鼠在螢幕上的座標。第一次點擊可記錄起始點,第二次點擊可記錄結束點,兩點之間即構成擷取範圍。
先取得螢幕寬高,再建立與擷取範圍相符的 Bitmap:
int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
使用 CopyFromScreen 時,可指定來源座標、目標座標與尺寸。若起點為 Fx、Fy,終點為 Fy,則可擷取:
gfx.CopyFromScreen(Fx.X, Fx.Y, 0, 0, new Size(Fy.X - Fx.X, Fy.Y - Fx.Y));
完成繪製後,可把 Bitmap 指定給 PictureBox 的 BackgroundImage,或存檔:
bmpScreenShot.Save("shot.png");
實作時要注意座標順序與寬高計算,避免範圍為負值。