BlogScreenshots on your device
How to Take Screenshots with Graphics.CopyFromScreen in C#
Capture a visible screen rectangle in C# with Graphics.CopyFromScreen, save it to an image, and handle coordinates, errors, and platform limits.

To take a screenshot in C# using Graphics.CopyFromScreen, create a bitmap for the region you want, create a Graphics object from that bitmap, copy pixels from the screen rectangle into the bitmap, then save the bitmap. The method copies a visible rectangular area of the screen; it is not a browser screenshot API or a way to capture an arbitrary hidden window.
using System.Drawing;
static void SaveScreenRegion(string path, int x, int y, int width, int height)
{
if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width));
if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height));
using var bitmap = new Bitmap(width, height);
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(x, y, 0, 0, bitmap.Size);
}
bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png);
}
SaveScreenRegion("capture.png", 100, 100, 800, 600);
The first coordinates are the screen rectangle’s upper-left point. The next point, (0, 0) above, is the destination’s upper-left point inside the bitmap. The final size is the rectangle copied. Microsoft describes the operation as transferring color data for a screen rectangle to a Graphics drawing surface. The full bitmap-backed save sequence above is practical implementation guidance built around that documented call. See the Microsoft API reference for overloads and applicability.
1. What CopyFromScreen captures
Graphics.CopyFromScreen copies screen pixels from a rectangular source area to a drawing surface. In the common screenshot pattern, that drawing surface belongs to a bitmap in memory. You decide the source position and size, and the bitmap provides the destination.
This means the source is the screen as rendered, not a document model or a page DOM. If the application is minimized, covered, or otherwise not visible in the captured rectangle, this method does not independently render its hidden contents. Choose this approach when the requirement is a visible desktop region and the application targets a supported Windows desktop environment.
2. Create a complete screenshot program
For a minimal console program, use a Windows-targeted project. For example, a modern .NET project can set its target framework to a Windows target and enable Windows Forms support:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>
Then put this in Program.cs. The example validates its rectangle, disposes native-backed drawing resources deterministically, and writes PNG output:
using System.Drawing;
using System.Drawing.Imaging;
if (args.Length != 5)
{
Console.Error.WriteLine("Usage: Capture <output.png> <x> <y> <width> <height>");
return 2;
}
if (!int.TryParse(args[1], out int x) ||
!int.TryParse(args[2], out int y) ||
!int.TryParse(args[3], out int width) ||
!int.TryParse(args[4], out int height) ||
width <= 0 || height <= 0)
{
Console.Error.WriteLine("Coordinates must be integers and dimensions must be positive.");
return 2;
}
try
{
using var bitmap = new Bitmap(width, height);
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(x, y, 0, 0, bitmap.Size);
}
bitmap.Save(args[0], ImageFormat.Png);
Console.WriteLine($"Saved {args[0]}");
return 0;
}
catch (System.ComponentModel.Win32Exception ex)
{
Console.Error.WriteLine($"Screen copy failed: {ex.Message}");
return 1;
}
Run it with the output path followed by the source screen origin and dimensions, for example Capture.exe capture.png 100 100 800 600. The path and format are application choices. The code saves PNG; for JPEG or another supported format, use the corresponding ImageFormat and a matching filename extension.
3. Understand source, destination, and size
| Argument | Meaning | Typical bitmap use |
|---|---|---|
| Source point | Upper-left screen coordinate to read from | x, y |
| Destination point | Upper-left coordinate on the drawing surface to write to | 0, 0 |
| Block size | Width and height of the rectangle to transfer | bitmap.Size |
Microsoft provides overloads taking Point values or integer coordinates. Some overloads also take CopyPixelOperation, which controls how source and destination colors are copied or blended. For a normal screenshot, the simplest overload with the default copy behavior is usually the clearest choice. Use a specialized raster operation only when the application specifically needs that blending behavior.

The destination point matters when drawing into a larger bitmap or another surface. For a bitmap that exactly matches the requested capture, (0, 0) places the copied rectangle at its top-left. If you use a destination offset, ensure the copied rectangle fits within the destination surface.
4. Capture a chosen rectangle or the desktop
For a region, pass its screen origin and dimensions directly. To capture a larger desktop area, define that area explicitly and create a bitmap with matching dimensions. The same workflow applies: allocate the destination, copy the selected rectangle, then save.

For multiple displays, decide which screen rectangle you intend to capture and size the destination accordingly. Display arrangements can place screens at coordinates beyond the primary display’s origin, including negative coordinates. The API’s coordinate arguments describe the source rectangle, but exact mixed-DPI behavior depends on the app and desktop configuration; verify the result on the target setup instead of assuming all display coordinates map identically.
A Windows Forms paint handler can also copy screen pixels to the form’s drawing surface. Microsoft’s example uses the form location as the source, destination position (40, 40), and a 100 x 100 block. For a saved screenshot, the bitmap destination pattern is easier to reason about because the output dimensions are explicit.
5. Save to different formats safely
PNG is a convenient default for screenshots when preserving crisp edges matters. JPEG may be suitable when smaller photographic output is more important and lossy compression is acceptable. Pick the encoder explicitly and keep the extension consistent:
bitmap.Save("capture.png", ImageFormat.Png);
// Or:
bitmap.Save("capture.jpg", ImageFormat.Jpeg);
Saving can fail for ordinary filesystem reasons, such as a missing output directory or insufficient write access. Those are distinct from a screen-copy failure. In production code, handle file I/O exceptions at the save boundary and report the path that failed without swallowing the error.
6. Resource management and reliability
Dispose both the Graphics object and bitmap. The using statements in the examples guarantee cleanup when the copy or save throws. Avoid retaining a new bitmap for every capture indefinitely; repeated allocations can consume memory and drawing-system resources.
Keep capture synchronous when a user explicitly requests a one-off image and the pause is acceptable. In an interactive application, run potentially slow capture and file writing away from a UI event handler if responsiveness matters, then marshal only UI updates back to the UI thread. Treat capture and save as separate operations so logs identify whether copying pixels or writing the file failed.
The API reference documents Win32Exception when the operation fails and InvalidEnumArgumentException when a supplied CopyPixelOperation value is invalid. It does not establish behavior for every secure desktop, remote session, protected surface, or headless environment. If a target environment is important, validate it there and provide a clear failure path.
7. Platform and project configuration
CopyFromScreen is documented for Windows Desktop platform versions, and the API page includes .NET Framework and .NET Standard applicability entries. That does not make this a universal cross-platform screen capture method. Check the target framework and operating system for the application you ship. For modern .NET, a Windows-specific target framework makes the platform intent explicit; avoid presenting a generic cross-platform project as guaranteed to support desktop capture.
When the compiler cannot resolve System.Drawing, check the target framework and the project’s Windows desktop configuration first. Framework packaging and project settings vary, so follow the official API applicability and platform guidance for the exact target you use.
8. Troubleshooting common errors
| Symptom | Likely cause | Fix |
|---|---|---|
Win32Exception during copy |
The underlying screen operation failed in the current environment. | Confirm the app runs in the intended Windows desktop session, check the requested rectangle, and log the exception details. The API reference identifies this exception but does not promise success in every desktop configuration. |
InvalidEnumArgumentException |
An invalid CopyPixelOperation value was passed. |
Use a documented enum value or use the overload without a raster-operation argument for ordinary copying. |
| Empty or unexpected image | Wrong source coordinates, dimensions, or destination point. | Log all four rectangle values, confirm width and height are positive, and inspect whether the source area contains the pixels you expect. |
| Part of the intended window is missing | The requested screen rectangle does not cover it, or another surface obscures it. | Capture the actual visible region and adjust the source rectangle. This method copies screen pixels rather than rendering a hidden window. |
| Save fails after a successful copy | Invalid path, unavailable directory, or write permissions. | Create or select a writable directory, handle file exceptions separately, and ensure the extension matches the chosen image format. |
| Works on one machine but not another | Different target framework, OS, display layout, or desktop session. | Verify the Windows-targeted build and test on the actual deployment environment. Do not infer mixed-DPI or remote-session behavior from the basic API description. |
9. Performance and cost considerations
The API reference defines what is copied but gives no comparative performance benchmark. The work scales with the rectangle being transferred in the practical sense that larger outputs require a larger bitmap and more image data to save; measure in the application’s real display and output conditions if capture latency matters. Keep the region no larger than needed, avoid unnecessary repeated captures, and choose an output format appropriate to the image and storage constraints.
There is no per-request service charge for a local CopyFromScreen call, though the application still uses CPU, memory, and disk or storage bandwidth. If the job is actually to capture a website page rather than the local visible desktop, the browser setup and environment are a different requirement.
10. Or skip the browser setup
For website screenshots, ScreenshotNeo is a website screenshot API and MCP server. It takes a URL in one GET request and returns PNG, JPEG, WebP, or PDF. Its browser capture flow can be more suitable when you need a page capture rather than pixels from your own desktop.
ScreenshotNeo API documentation
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
- Cookie and consent banners are accepted like a visitor, and more than 60 known consent platforms, newsletter popups, and chat widgets are removed before the shot; each step can be turned off.
- Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing. The response identifies page verdict and billing status in headers.
- An MCP server gives AI agents tools for screenshots, page information, and PDF capture.
- The free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000; every feature is on every plan.
Create a free ScreenshotNeo account for 1,000 screenshots a month with no card.
11. FAQ
Can CopyFromScreen save directly to a file?
No. It copies into a drawing surface. Create a bitmap-backed surface, copy into it, then save that bitmap using an image format.
Can I capture a browser page with this method?
Only insofar as the browser is visible in the screen rectangle. It captures displayed screen pixels, not the page’s underlying content or a full-page browser rendering.
Which overload should I start with?
Use the integer-coordinate or Point overload without CopyPixelOperation for a straightforward screenshot. Add a raster operation only when you need its documented copy or blend behavior.
Is it supported on non-Windows systems?
The cited API reference lists Windows Desktop support. Treat the method as Windows desktop functionality and confirm support for your specific target framework and deployment platform.
12. Implementation checklist
- Choose the exact visible screen rectangle and validate positive dimensions.
- Allocate a bitmap whose dimensions match the desired output.
- Copy from the screen origin to the bitmap destination, normally
(0, 0). - Dispose the bitmap and
Graphicsobject even if an operation fails. - Save with an explicit image format and handle copy errors separately from file errors.
- Test on the Windows desktop configuration and display layout you intend to support.


