For a visible window, get its screen coordinates, create a Bitmap, and call Graphics.CopyFromScreen. If you need to target a window by its HWND or avoid copying pixels covered by another window, use Win32 PrintWindow. For newer Windows capture workflows, Windows.Graphics.Capture can target an HWND directly.
The right method depends on what “capture” means: desktop pixels, an owner-rendered window, or a modern capture frame. The examples below show complete, disposable C# code for each choice, explain occlusion and failure cases, and include a web-URL alternative when a browser screenshot is all you need.
Choose the capture method first
| Approach | What it captures | Occlusion | Targeting | Main trade-off |
|---|---|---|---|---|
Graphics.CopyFromScreen |
Pixels currently displayed on the desktop | Another window can cover the target pixels | Any screen-space rectangle | Simple managed code, but the content must be visible |
Win32 PrintWindow |
Image rendered by the window owner into your device context | Does not depend solely on desktop pixels; support varies by application | HWND, optionally client area only | P/Invoke, HDC lifetime, and a synchronous call |
Windows.Graphics.Capture |
Frames from the modern Windows capture pipeline | Uses Windows capture semantics rather than a screen-copy operation | HWND or HMONITOR | More WinRT interop and frame-pool setup |
Option 1: capture a visible rectangle with CopyFromScreen
Graphics.CopyFromScreen performs a bit-block transfer from a rectangle of screen pixels to a drawing surface. It is the shortest solution when your application already knows the target window’s screen-space bounds and the window is visible.
Complete WinForms example
This example captures a named WinForms window, saves a PNG, and disposes every managed object deterministically.
Recommended Free Tools
#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;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Windows.Forms;
static class WindowShot
{
public static void Capture(Form target, string fileName)
{
Rectangle bounds = target.Bounds;
if (bounds.Width <= 0 || bounds.Height <= 0)
throw new InvalidOperationException("The window has no capturable area.");
using var bitmap = new Bitmap(
bounds.Width,
bounds.Height,
PixelFormat.Format32bppArgb);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(
bounds.Left,
bounds.Top,
0,
0,
bounds.Size,
CopyPixelOperation.SourceCopy);
}
bitmap.Save(fileName, ImageFormat.Png);
}
}
Call WindowShot.Capture(this, "window.png") from a form, or pass another visible form. For a Win32 window, obtain its rectangle with GetWindowRect and use the returned left, top, width, and height in the same pattern.
When CopyFromScreen is the wrong tool
- A different window overlaps the target: the overlapping pixels are copied.
- The window is minimized, off-screen, or otherwise not displayed: there may be nothing useful to copy.
- You need the title bar excluded: calculate a client rectangle instead of using the complete window bounds.
- The call fails at the operating-system level: handle the possible
Win32Exceptionand report the target rectangle and display state.
This is a desktop-pixel operation, not an off-screen renderer. Move or expose the target first when visual fidelity matters.
Option 2: capture an HWND with Win32 PrintWindow
PrintWindow accepts an HWND and a destination device context (DC), then asks the owning application to render its window into that DC. With flag 0, the normal result includes the complete window. With PW_CLIENTONLY (0x00000001), request only the client area.
Runnable P/Invoke implementation
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public static class PrintWindowShot
{
private const uint PW_CLIENTONLY = 0x00000001;
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool PrintWindow(
IntPtr hWnd,
IntPtr hdcBlt,
uint nFlags);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(
IntPtr hWnd,
out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
public static void Capture(IntPtr hwnd, string fileName, bool clientOnly = false)
{
if (hwnd == IntPtr.Zero)
throw new ArgumentException("The HWND is zero.", nameof(hwnd));
if (!GetWindowRect(hwnd, out RECT rect))
throw new InvalidOperationException("GetWindowRect failed.");
int width = rect.Right - rect.Left;
int height = rect.Bottom - rect.Top;
if (width <= 0 || height <= 0)
throw new InvalidOperationException("The window has no capturable bounds.");
using var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
using Graphics graphics = Graphics.FromImage(bitmap);
IntPtr hdc = graphics.GetHdc();
try
{
uint flags = clientOnly ? PW_CLIENTONLY : 0;
if (!PrintWindow(hwnd, hdc, flags))
throw new InvalidOperationException("PrintWindow returned false.");
}
finally
{
graphics.ReleaseHdc(hdc);
}
bitmap.Save(fileName, ImageFormat.Png);
}
}
Use a real window handle, for example one obtained from a WinForms control’s Handle property. Release the HDC in a finally block before saving or disposing the bitmap. Check the Boolean return value; a false result is a capture failure, not a valid blank screenshot.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →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
How PrintWindow behaves
The call is synchronous. The owning application processes the request and renders in your DC, receiving WM_PRINT or WM_PRINTCLIENT according to the flags. Do not make this call on a UI-interaction thread if a slow or unresponsive target could freeze your interface; run it on a worker and apply your own timeout policy.
Rendering support is application-dependent. Custom-drawn, hardware-accelerated, protected, minimized, or unusual windows can return incomplete, black, or otherwise unexpected images. PrintWindow is therefore not a universal guarantee of an off-screen-perfect frame.
Finding the window and choosing its area
Use a framework handle when you own the window
In WinForms, a form or control exposes Handle. In WPF, obtain the native handle from the containing Window with WindowInteropHelper, then pass that IntPtr to the P/Invoke method. Ensure the native window has been created before reading the handle.
Use screen bounds for desktop capture
CopyFromScreen needs coordinates in screen space. A window’s Left and Top are not always the same coordinate system as a framework’s logical, DPI-scaled units. Convert to device pixels when your framework exposes logical units, and test on a monitor whose scaling differs from 100 percent.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteRank #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.
Full window versus client area
The full HWND rectangle includes non-client chrome such as the title bar and borders. Pass PW_CLIENTONLY to PrintWindow when you want only the client region. With CopyFromScreen, obtain the framework’s client rectangle and translate it to screen coordinates before copying.
Option 3: Windows.Graphics.Capture for modern Windows apps
On Windows 10 version 1803 and later capture stacks, Windows.Graphics.Capture provides a modern frame pipeline. Interop extensions let a desktop application target one HWND or an HMONITOR. A Win32 app supplies its HWND to the capture picker, creates a frame pool, and consumes frames rather than receiving a one-shot GDI bitmap.
Choose this route when you already use WinRT or WinUI interop, need a stream of frames, or want the modern Windows capture model. It requires substantially more setup than either example above: graphics-device creation, frame-pool sizing, frame-arrival handling, synchronization, and conversion or encoding. For a single PNG from a conventional desktop app, start with CopyFromScreen or PrintWindow.
Saving, resource lifetime, and image format
- Save explicitly with
bitmap.Save(path, ImageFormat.Png), or choose JPEG/WebP through a suitable encoder in your application. - Use
usingorusing varforBitmapandGraphics. - Always pair
GetHdcwithReleaseHdc, even whenPrintWindowthrows. - Create the destination bitmap with dimensions greater than zero and a known pixel format such as
Format32bppArgb. - Write to a location where the process has permission, and close or replace an existing file according to your application’s policy.
Troubleshooting common failures
The screenshot contains another window
You used CopyFromScreen while the target was occluded. Bring the window to the foreground or switch to PrintWindow, understanding that the owner must support the render request.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →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
PrintWindow returns false
Verify that the HWND is valid and the window still exists. Confirm that the bitmap dimensions are positive, the HDC was acquired successfully, and the call is made from a process allowed to interact with the target. Log Marshal.GetLastWin32Error() immediately after a failed native call when you need additional diagnostics.
The image is black or incomplete
The target may use protected content, custom composition, hardware acceleration, or a rendering path that does not respond fully to WM_PRINT. Try a visible CopyFromScreen capture, or move to Windows.Graphics.Capture for a modern pipeline.
The capture freezes the application
PrintWindow is synchronous and can wait for the owner. Execute it away from your UI thread, limit how long your worker can block, and treat a timed-out operation as a failed capture that requires cleanup.
The output is cropped or the wrong size
Check DPI conversion, multi-monitor coordinates, and whether you intended the client area or the complete window. Log the rectangle immediately before allocating the bitmap.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
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.
Performance and reliability decisions
For occasional visible-window snapshots, CopyFromScreen has the least setup. Repeated captures add bitmap allocation, encoding, and disk-I/O costs; reuse buffers only when their dimensions and lifetime are controlled safely. PrintWindow shifts work to the target process and can block unpredictably, so it is less suitable for an unbounded capture loop without cancellation and back-pressure. A frame-pool design with Windows.Graphics.Capture is the better architectural fit for continuous recording, but it demands more interop and synchronization code.
Or skip the browser setup
The C# methods above capture Windows desktop applications by rectangle or HWND. If your actual input is a web URL, ScreenshotNeo returns a screenshot or PDF with one GET request and avoids maintaining a browser automation stack. It removes cookie and consent banners, newsletter popups, and chat widgets before the capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed as clean shots. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.
See the ScreenshotNeo API documentation for parameters and authentication. A direct call looks like this:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Equivalent Python:
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)
And Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Create a free ScreenshotNeo account to start with 1,000 screenshots a month and no card.
Free tools Windows power users keep installed
One-click scans. No signup required.
Frequently Asked Questions
Can CopyFromScreen capture a minimized window?
No. It copies pixels currently present on the desktop, so a minimized or undisplayed window does not provide its normal visible content.
Which flag captures only the client area with PrintWindow?
Pass the constant PW_CLIENTONLY, whose value is 0x00000001.
Is PrintWindow guaranteed to capture every application?
No. The owning application renders the result, and custom, protected, accelerated, or unusual windows may produce incomplete output.
When should I use Windows.Graphics.Capture?
Use it when you need modern HWND or monitor capture, a stream of frames, or an existing WinRT/WinUI interop architecture rather than a one-shot bitmap.
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.

