CopyFromScreen
是一個非常有用的方法,它可以將屏幕上的某個區域復制到一個 Bitmap
對象中。這在創建屏幕截圖、錄制屏幕或進行自動化測試時非常有用。以下是一些使用 CopyFromScreen
的技巧和示例:
using System.Drawing;
using System.Windows.Forms;
public Bitmap CaptureScreen()
{
Rectangle screenBounds = Screen.GetBounds(Point.Empty);
Bitmap screenshot = new Bitmap(screenBounds.Width, screenBounds.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(screenshot))
{
g.CopyFromScreen(Point.Empty, Point.Empty, screenBounds.Size);
}
return screenshot;
}
public Bitmap CaptureRegion(Rectangle region)
{
Bitmap screenshot = new Bitmap(region.Width, region.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(screenshot))
{
g.CopyFromScreen(region.Location, Point.Empty, region.Size);
}
return screenshot;
}
public Bitmap CaptureTransparentScreenshot(Rectangle region)
{
Bitmap screenshot = new Bitmap(region.Width, region.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(screenshot))
{
g.CopyFromScreen(region.Location, Point.Empty, region.Size, CopyPixelOperation.SourceCopy);
}
return screenshot;
}
public Bitmap HighlightRegion(Bitmap screenshot, Rectangle region, Color highlightColor)
{
using (Graphics g = Graphics.FromImage(screenshot))
{
using (Pen pen = new Pen(highlightColor, 5))
{
g.DrawRectangle(pen, region);
}
}
return screenshot;
}
public void SaveScreenshot(Bitmap screenshot, string filePath)
{
screenshot.Save(filePath, ImageFormat.Png);
}
public void DisplayScreenshot(Form form, Bitmap screenshot)
{
form.BackgroundImage = screenshot;
form.ClientSize = screenshot.Size;
}
這些技巧和示例可以幫助你更好地使用 CopyFromScreen
方法。記住,當你處理大量圖像時,要確保正確地釋放資源,以避免內存泄漏。