Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To draw a rectangular outline on an existing screenshot in C#, load it into a Bitmap, create a Graphics object from that bitmap, and call DrawRectangle with a Pen and a Rectangle. The example below saves a new PNG and targets Windows: System.Drawing.Common is Windows-specific starting with .NET 6. If you need to capture the desktop as well as annotate it, use Graphics.CopyFromScreen first, then draw on the resulting bitmap.
Draw a rectangle on an existing screenshot
The following console program takes an input image, an output path, and a rectangle expressed in the image’s pixel coordinates. It draws a red outline and writes a PNG. Keeping the input and output paths separate avoids problems that can occur if you try to overwrite an image while it is still open.
Set up a Windows project
Use a stable Windows target framework, such as .NET 8. In the project file, enable the Windows desktop framework reference so the program can use System.Drawing:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Save this as Program.cs. The program accepts six arguments: input image, output PNG, x, y, width, and height. For example, run dotnet run -- input.png marked.png 100 80 300 180.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
using System.Drawing;
using System.Drawing.Imaging;
if (args.Length != 6)
{
Console.Error.WriteLine("Usage: dotnet run -- <input-image> <output.png> <x> <y> <width> <height>");
return 2;
}
if (!int.TryParse(args[2], out int x) ||
!int.TryParse(args[3], out int y) ||
!int.TryParse(args[4], out int width) ||
!int.TryParse(args[5], out int height) ||
width <= 0 || height <= 0)
{
Console.Error.WriteLine("x and y must be integers; width and height must be positive integers.");
return 2;
}
try
{
using var screenshot = new Bitmap(args[0]);
// Check the rectangle against the bitmap dimensions before drawing.
if (x < 0 || y < 0 || x + (long)width > screenshot.Width || y + (long)height > screenshot.Height)
{
Console.Error.WriteLine($"Rectangle must fit within the {screenshot.Width}x{screenshot.Height} image.");
return 2;
}
using (Graphics graphics = Graphics.FromImage(screenshot))
using (var pen = new Pen(Color.Red, 4))
{
graphics.DrawRectangle(pen, new Rectangle(x, y, width, height));
}
screenshot.Save(args[1], ImageFormat.Png);
Console.WriteLine($"Saved annotated image to {args[1]}");
return 0;
}
catch (ArgumentException ex)
{
Console.Error.WriteLine($"Could not read the input image or draw the rectangle: {ex.Message}");
return 1;
}
catch (IOException ex)
{
Console.Error.WriteLine($"Could not read or write a file: {ex.Message}");
return 1;
}
Bitmap holds the pixels being edited. Graphics.FromImage(screenshot) creates a drawing surface for that bitmap; this is different from drawing in a Windows Forms paint event, where the control supplies a graphics object for painting the live interface. DrawRectangle draws an outline, and the Pen determines its color and stroke width. Dispose the graphics and pen when finished, as the code does, and do not use the bitmap after it has been disposed.
Choose the rectangle’s coordinates and appearance
Use the screenshot’s coordinate space
A Rectangle consists of an upper-left location and a width and height. Its coordinates should describe pixels in the bitmap, not positions in a window, browser, or preview unless those coordinate systems happen to match. By default, drawing units are pixels; graphics settings such as PageUnit and PageScale can change how coordinates are interpreted.
If a person selects a box on a preview displayed at a different size, convert the selection before calling DrawRectangle. For a preview scaled uniformly from bitmap dimensions imageWidth × imageHeight to previewWidth × previewHeight, a preview point (px, py) maps approximately to (px × imageWidth / previewWidth, py × imageHeight / previewHeight). Apply the same scale to the selected width and height, and account for any padding or letterboxing around the image. Round the resulting values consistently to integer pixels.
Account for the pen stroke
The rectangle describes a path, and the pen stroke is centered on that path. A four-pixel pen therefore extends on both sides of the nominal border. If the rectangle lies exactly on the image edge, part of a thick stroke can be clipped or fall outside the intended area. Leave room for the stroke by moving the rectangle inward, or use a thinner pen. Increase the width for a large or high-resolution screenshot, but check the saved result at its intended display size.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Outline versus filled highlight
Use DrawRectangle(pen, rectangle) for a border. To cover the rectangle with a solid color, use FillRectangle(brush, rectangle) instead; a brush fills the area, while a pen traces the outline. A filled brush is opaque unless you deliberately configure a color with an alpha component and use an implementation that supports the intended compositing. If you need a translucent highlight, test it on the target framework and verify the saved output, rather than assuming that a normal fill will preserve visibility beneath it.
Capture the desktop before annotating
Capturing and annotating are separate operations. Graphics.CopyFromScreen transfers a specified rectangle of display pixels into a drawing surface. Its source point identifies where on the screen to copy from, its destination point identifies where in the bitmap to place those pixels, and its size determines the copied area.
This optional Windows example captures a region, draws an outline into the in-memory bitmap, and saves it as a PNG. It assumes the requested source rectangle is within the display area available to the process; it does not provide multi-monitor coordinate discovery.
using System.Drawing;
using System.Drawing.Imaging;
int screenX = 100;
int screenY = 100;
int captureWidth = 800;
int captureHeight = 600;
var captureSize = new Size(captureWidth, captureHeight);
var mark = new Rectangle(40, 50, 240, 120);
using var screenshot = new Bitmap(captureWidth, captureHeight);
using (Graphics graphics = Graphics.FromImage(screenshot))
{
graphics.CopyFromScreen(
new Point(screenX, screenY),
Point.Empty,
captureSize);
using var pen = new Pen(Color.Red, 4);
graphics.DrawRectangle(pen, mark);
}
screenshot.Save("desktop-marked.png", ImageFormat.Png);
The mark coordinates here are relative to the captured bitmap: its top-left is the destination origin. Adjust screenX, screenY, and the capture size to choose another source region. If the copy operation fails, the exception may be a Win32Exception; the exact behavior can depend on the Windows environment and how the application is run.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Save the annotated image in the format you need
Save only after drawing is complete. In the main example, ImageFormat.Png explicitly writes PNG data even if the output filename does not end in .png. Use the matching ImageFormat when you want another supported output format. PNG is a practical choice for screenshots with text and sharp edges; JPEG uses lossy compression, which can soften fine interface details.
- Keep the original file if the annotation should be reversible; write to a distinct output path.
- Make sure the destination directory exists and that the process can write there.
- Dispose the bitmap after saving. If you need to keep editing, do not dispose it until all drawing and saves are finished.
- When processing many images, dispose each bitmap and its graphics resources before moving to the next file to release native resources promptly.
Platform and workflow choices
Windows applications using System.Drawing
This guide’s System.Drawing.Common approach is for Windows. Microsoft identifies the library as Windows-specific beginning with .NET 6. Do not treat older non-Windows workarounds or compatibility switches as general current support. If your application must run on Linux or macOS, choose a cross-platform graphics library that supports your target platforms and verify its maintenance, licensing, and supported frameworks before adopting it.
Manual capture and markup
If you only need to mark up one screenshot and do not need repeatable automation, Windows Snipping Tool can capture a rectangular region and offers drawing, shapes, erasing, cropping, and saving after capture. A C# program is more useful when the rectangle must be applied consistently, coordinates come from another process, or images need to be generated in a workflow.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteOr skip the browser setup
If the screenshot you need is of a webpage rather than the desktop, ScreenshotNeo can capture the page through one API request. It does not draw the rectangle for you: download the resulting image, then use the C# annotation code above to mark it. Cookie banners are accepted and removed before the shot, and known newsletter popups and chat widgets are removed; those cleanup steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, with page and billing outcomes indicated in response headers. ScreenshotNeo also offers an MCP server with screenshot tools for AI agents.
Here is the cURL request from the ScreenshotNeo API documentation:
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Free includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free. Every feature is on every plan. This is a webpage-capture option, not a substitute for CopyFromScreen when you need pixels from a local desktop.
Sign up free for 1,000 screenshots a month, with no card required.
Troubleshooting
The project cannot find System.Drawing
Check that the project targets Windows, uses a Windows target framework such as net8.0-windows, and has UseWindowsForms enabled as shown above. A plain cross-platform target is not enough to make this Windows-specific drawing approach portable.
The rectangle is missing, shifted, or the wrong size
Confirm that x and y refer to the screenshot bitmap’s top-left origin and that width and height are positive. If coordinates came from a scaled preview or a UI control, map them into bitmap coordinates first. Check for preview margins, nonuniform scaling, or a changed PageUnit or PageScale.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
The border is partly cut off
The pen is centered on the rectangle path, so a stroke near an edge can extend beyond the image. Move the rectangle inward by roughly half the pen width or reduce the stroke width.
The image does not save
Check that the output directory exists, the output file is not locked by another process, and the current user has write access. Save to a new filename while testing rather than overwriting the input image. Confirm the selected image format matches the output you expect.
Recommended Free Tools
Desktop capture throws an exception
Check that the source coordinates and requested dimensions describe a valid region of the active display and that the destination bitmap is large enough. CopyFromScreen can fail with a Win32Exception; inspect the exception details in the actual Windows environment rather than assuming all desktop sessions permit the same capture behavior.
Frequently asked questions
Can I draw a rectangle directly in a Windows Forms paint event?
Yes. A paint event draws into a control for display. To edit and save screenshot pixels, draw into a graphics object created from the screenshot bitmap, as in the examples above.
Does DrawRectangle fill the box?
No. It draws an outline. Use FillRectangle with a brush when the rectangle’s interior should be colored.
Can I use this approach on Linux or macOS?
Not as a supported general System.Drawing.Common solution starting with .NET 6. Use a graphics library that explicitly supports the platforms your application targets.
Can I annotate only one object in the screenshot?
Yes. Set the rectangle’s coordinates and dimensions to cover that object, or identify those values in your application before calling the drawing method. The drawing API paints the specified geometry; it does not detect objects by itself.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

