October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
C++

How to Capture a Specific Window Screenshot in C# (HWND, CopyFromScreen, and PrintWindow)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Graphics.CopyFromScreen when you need the pixels currently visible on the desktop, and use Win32 PrintWindow when you need to target a window by its HWND. For new Windows capture workflows, Windows.Graphics.Capture is the modern option for an individual window or monitor. The right choice depends on whether the window must be visible, whether another window may cover it, and how much interop code your application can support.

Choose the capture method first

Approach Source image Occlusion Area control Trade-off
CopyFromScreen Pixels displayed on the desktop Covered pixels can be copied Any screen rectangle Simple managed code, but content must be visible
PrintWindow Image rendered by the HWND owner May work when not relying on visible desktop pixels; application support varies Full window or client area Requires P/Invoke and synchronous native rendering
Windows.Graphics.Capture Frames from the modern Windows capture pipeline Uses Windows capture semantics HWND or monitor Best for modern frame-pool applications, with more interop setup

Microsoft’s Graphics.CopyFromScreen documentation describes a bit-block transfer from a screen rectangle to a Graphics surface. The PrintWindow Win32 API reference documents rendering a visual window into a supplied device context.

Option 1: capture visible pixels with CopyFromScreen

This is the shortest solution for WinForms, and it also works in other Windows desktop projects that can obtain a screen-space rectangle. Get the target window’s Left, Top, Width, and Height, allocate a bitmap, and copy the corresponding desktop rectangle.

Complete WinForms example

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

public static class WindowScreenshot
{
    public static void CaptureVisible(Rectangle bounds, string fileName)
    {
        if (bounds.Width <= 0 || bounds.Height <= 0)
            throw new ArgumentException("The window bounds must have a positive size.", nameof(bounds));

        using var bitmap = new Bitmap(
            bounds.Width,
            bounds.Height,
            PixelFormat.Format32bppArgb);

        using (var graphics = Graphics.FromImage(bitmap))
        {
            graphics.CopyFromScreen(
                bounds.Left,
                bounds.Top,
                0,
                0,
                bounds.Size,
                CopyPixelOperation.SourceCopy);
        }

        bitmap.Save(fileName, ImageFormat.Png);
    }
}

// Example: the current form, including its visible desktop area.
Rectangle formBounds = this.Bounds;
WindowScreenshot.CaptureVisible(formBounds, "window.png");

For a different WinForms window, use its Bounds property. With WPF, convert the window’s device-independent coordinates to screen pixels before calling this method; per-monitor DPI settings can otherwise produce an incorrectly sized bitmap. A rectangle that crosses monitors is valid, but each monitor can have different scaling.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall

What this method really captures

  • It copies what is displayed at the requested screen coordinates, not an abstract window surface.
  • If another window covers the target, the covering pixels may appear in the file.
  • Minimizing or moving the target off-screen prevents a useful desktop-pixel capture.
  • Microsoft documents that the operation can raise Win32Exception when the transfer fails.

Option 2: capture an HWND with PrintWindow

PrintWindow accepts an HWND and a destination device context. The owning application receives a request to render into that context, so this approach does not depend solely on the pixels currently visible on your desktop. It is synchronous: a slow or uncooperative application can make the call take a long time.

Full-window and client-area code

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

public static class PrintWindowCapture
{
    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);

    public static void Capture(IntPtr hwnd, Rectangle bounds, string fileName, bool clientOnly = false)
    {
        if (hwnd == IntPtr.Zero)
            throw new ArgumentException("The HWND cannot be zero.", nameof(hwnd));
        if (bounds.Width <= 0 || bounds.Height <= 0)
            throw new ArgumentException("The window bounds must have a positive size.", nameof(bounds));

        using var bitmap = new Bitmap(
            bounds.Width,
            bounds.Height,
            PixelFormat.Format32bppArgb);
        using var graphics = Graphics.FromImage(bitmap);
        IntPtr hdc = graphics.GetHdc();
        try
        {
            bool rendered = PrintWindow(
                hwnd,
                hdc,
                clientOnly ? PW_CLIENTONLY : 0);
            if (!rendered)
                throw new InvalidOperationException("PrintWindow returned false.");
        }
        finally
        {
            graphics.ReleaseHdc(hdc);
        }

        bitmap.Save(fileName, ImageFormat.Png);
    }
}

Pass 0 to request the default full window, including non-client chrome such as the title bar. Pass PW_CLIENTONLY (0x00000001) to request only the client area. Obtain the HWND and matching bounds from your UI framework or Win32 enumeration APIs, then call PrintWindowCapture.Capture(hwnd, bounds, "window.png").

Important PrintWindow limitations

  • Always check the Boolean return value; false means the capture failed.
  • The call is synchronous. Do not invoke it on a UI-interaction thread if a target application may be slow, because your application can appear unresponsive.
  • Custom rendering, hardware acceleration, protected content, minimized windows, and unusual applications may produce incomplete or blank output. The API contract does not guarantee identical results for every owner.
  • Release the HDC in a finally block before saving or disposing the bitmap. Dispose every Graphics and Bitmap deterministically.

Option 3: Windows.Graphics.Capture for modern Windows apps

On Windows 10 version 1803 and later capture stacks, Windows.Graphics.Capture provides a modern pipeline for a single window or monitor. Microsoft documents interop extensions that target an HWND or HMONITOR. A Win32 application can provide its HWND to the capture picker, as shown in Microsoft’s screen-capture guidance and the Win32 capture sample.

Rank #2
Dell Latitude 3190 11.6" HD 2-in-1 Touchscreen Laptop Intel N5030 1.1Ghz 4GB Ram 128GB SSD Windows 11 Professional (Renewed)
  • 1.1 GHz (boost up to 2.4GHz) Intel Celeron N5030 Quad-Core
  • 4GB DDR4 System Memory; 128GB Solid State Drive
  • 11.6" HD (1366 x 768) Multi-Touch Display
  • Combo headphone/microphone jack - Noble Wedge Lock slot - HDMI; 2 USB 3.1 Gen 1
  • Windows 11 Pro

Choose this route when you already use WinRT/WinUI interop, need repeated frames, or want a frame-pool workflow. A one-shot PNG is usually less code with the first two options. You must handle the capture item, frame pool, session, pixel format, and conversion to your desired image format; the exact setup differs between .NET desktop project types.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Finding the correct window and rectangle

  • Your own WinForms form: use form.Handle for the HWND and form.Bounds for screen coordinates.
  • Your own WPF window: obtain the HWND with WindowInteropHelper(window).Handle; use a screen-coordinate API such as GetWindowRect for native bounds.
  • Another process: enumerate or locate its top-level HWND, verify it is still valid immediately before capture, and expect permission, DPI, and custom-rendering differences.
  • Client-only output: use PW_CLIENTONLY with PrintWindow, or calculate the client rectangle and use CopyFromScreen if the client area is visibly exposed.

Troubleshooting checklist

The image contains another window

You used desktop-pixel capture while the target was occluded. Move or expose the window, or try PrintWindow. Owner rendering is application-dependent, so test the target application rather than assuming it will work.

The output is black, blank, or incomplete

Check the HWND, bounds, return value, and bitmap dimensions. Some accelerated, protected, minimized, or custom-rendered windows do not provide a complete PrintWindow result. Try a visible CopyFromScreen capture or the modern Windows capture pipeline.

Rank #3
Dell Latitude 5420 14" FHD Business Laptop Computer, Intel Quad-Core i5-1145G7, 16GB DDR4 RAM, 256GB SSD, Camera, HDMI, Windows 11 Pro (Renewed)
  • 256 GB SSD of storage.
  • Multitasking is easy with 16GB of RAM
  • Equipped with a blazing fast Core i5 2.00 GHz processor.

The capture hangs

PrintWindow is synchronous and can wait for the owning application. Run it away from your UI thread, impose an application-level timeout policy, and avoid capturing unresponsive targets indefinitely.

The image is the wrong size

Check per-monitor DPI scaling and distinguish device-independent WPF units from physical pixels. Use native screen bounds for the bitmap dimensions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

CopyFromScreen throws an exception

Validate that the rectangle is positive, the display is available, and the process has not entered a desktop or session state where screen access fails. Log the exception and the rectangle you attempted to copy.

Rank #4
15.6 Inch Laptop Computer, N4020, 4GB DDR4 RAM, 128GB eMMC,with Windows 11
  • EFFORTLESS EVERYDAY PERFORMANCE: Powered by Intel Celeron N4020 processor and Windows 11 Home system, delivering reliable, low-power efficiency for daily tasks like document editing, email, online classes, and web browsing
  • 15.6-INCH FULL HD DISPLAY: Enjoy immersive visuals on the 15.6" FHD (1920x1080) anti-glare screen with micro-edge bezels. Delivers clear details and comfortable viewing for long study sessions, working on spreadsheets, and video playback
  • RESPONSIVE MULTITASKING & STORAGE: Built with 4GB LPDDR4 RAM and 128GB eMMC storage for smooth daily essential use. Expand your storage by up to 1TB via the integrated TF card slot to easily store movies, photos, and working files
  • ADVANCED CONNECTIVITY: Outfitted with 2x Full-Featured Type-C ports for data transfer, fast charging, and dual-monitor output, alongside 2x USB 3.2 Gen1 ports and a 3.5mm audio jack for complete peripheral compatibility
  • LIGHTWEIGHT & SILENT OPERATION: Slim and portable for effortless travel or commuting. Features a 1MP HD webcam for remote meetings, 38Wh battery with 45W Type-C fast charging, and a fanless silent design for peaceful work environments.

Save, performance, and reliability notes

PNG is lossless and convenient for diagnostics; JPEG is smaller but loses detail; WebP may be appropriate when your image pipeline supports it. Allocate only the required rectangle, reuse buffers for repeated captures when practical, and avoid saving on the UI thread. For repeated frame acquisition, Windows.Graphics.Capture is generally a better architectural fit than starting a new GDI operation for every frame. Treat every native handle and disposable managed object as a resource with a clear owner.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If the “window” you need is a webpage, ScreenshotNeo captures a URL with one request instead of maintaining browser automation. It accepts and removes cookie-consent banners, newsletter popups, and chat widgets before the shot; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server lets Claude, Cursor, and other MCP clients use take_screenshot, get_page_info, and capture_pdf.

See the ScreenshotNeo API documentation for all options, including full-page lazy-image loading, CSS-selector elements, dark mode, device presets, retina scale, PDF settings, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, authorization, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed links, asynchronous webhooks, bulk capture, usage reporting, and OpenAPI compatibility.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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}`);

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.

Best Value
Sale
15.6 Inch Win 11 Laptop Computer, N4020, 4GB DDR4 RAM, 128GB Storage
  • WINDOWS 11 | STABLE PERFORMANCE: Powered by Intel Celeron N4020 processor and Windows 11 system, this laptop delivers stable performance for everyday computing tasks. It supports web browsing, online learning, document editing, email communication, and basic office work with optimized power efficiency, providing a practical and reliable experience for essential daily use for daily use.
  • 15.6” FHD IPS DISPLAY: Features a 15.6-inch Full HD IPS display with narrow bezels, offering wider viewing angles and clearer image details compared to standard panels. The improved screen-to-body ratio enhances visual experience for study, reading, document work, and video playback, making it suitable for both productivity and entertainment use.
  • 4GB DDR4 + 128GB eMMC STORAGE: Equipped with 4GB DDR4 memory and 128GB eMMC storage for everyday basics such as browsing, documents, email, and online learning platforms. The built-in TF card slot supports storage expansion up to 1TB, giving you more flexibility for files, photos, videos, and daily documents. TF card not included.
  • CONNECTIVITY & PORTS: Includes 1× TF card slot, 2× USB 3.2 Gen1 ports, and 2× full-featured Type-C ports (USB 3.2 Gen1). The Type-C ports support data transfer, charging, and video output, enabling flexible connection with external devices such as monitors, storage, and peripherals for daily work and study use.
  • LIGHTWEIGHT DESIGN | ONLINE COMMUNICATION: Designed with a slim, portable profile, this laptop is easy to carry for school, commuting, and travel. A built-in 1MP front camera supports online classes, video meetings, remote communication, and everyday conferencing. The 3300mAh battery works with the low-power system design to support practical daily use, while thermal optimization helps maintain quieter operation during extended tasks.

Frequently asked questions

Can I capture a window using only its HWND?

Yes. Use the HWND with PrintWindow, allocate a bitmap using the window’s dimensions, and pass the bitmap’s device context to the API.

Does PrintWindow always capture minimized windows?

No. Rendering behavior varies by application, and minimized or protected content may be blank or incomplete.

Which method should I use for a visible WinForms window?

Start with CopyFromScreen when the window is exposed and you need exactly the desktop pixels. Use PrintWindow when targeting an HWND matters more than desktop occlusion.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I capture a window using only its HWND?

Yes. Use the HWND with PrintWindow, allocate a bitmap using the window’s dimensions, and pass the bitmap’s device context to the API.

Does PrintWindow always capture minimized windows?

No. Rendering behavior varies by application, and minimized or protected content may be blank or incomplete.

Which method should I use for a visible WinForms window?

Start with CopyFromScreen when the window is exposed and you need exactly the desktop pixels. Use PrintWindow when targeting an HWND matters more than desktop occlusion.

Quick Recap

Bestseller No. 1
HP 14' HD Laptop, Windows 11, Intel Celeron Dual-Core Processor Up to 2.60GHz, 4GB RAM, 64GB SSD, Webcam, Dale Pink (Renewed)
HP 14" HD Laptop, Windows 11, Intel Celeron Dual-Core Processor Up to 2.60GHz, 4GB RAM, 64GB SSD, Webcam, Dale Pink (Renewed)
14" diagonal, 1366x768 resolution, HD BrightView LED, Glossy NON-TOUCH Display
$249.99
Bestseller No. 2
Dell Latitude 3190 11.6' HD 2-in-1 Touchscreen Laptop Intel N5030 1.1Ghz 4GB Ram 128GB SSD Windows 11 Professional (Renewed)
Dell Latitude 3190 11.6" HD 2-in-1 Touchscreen Laptop Intel N5030 1.1Ghz 4GB Ram 128GB SSD Windows 11 Professional (Renewed)
1.1 GHz (boost up to 2.4GHz) Intel Celeron N5030 Quad-Core; 4GB DDR4 System Memory; 128GB Solid State Drive
Bestseller No. 3
Dell Latitude 5420 14' FHD Business Laptop Computer, Intel Quad-Core i5-1145G7, 16GB DDR4 RAM, 256GB SSD, Camera, HDMI, Windows 11 Pro (Renewed)
Dell Latitude 5420 14" FHD Business Laptop Computer, Intel Quad-Core i5-1145G7, 16GB DDR4 RAM, 256GB SSD, Camera, HDMI, Windows 11 Pro (Renewed)
256 GB SSD of storage.; Multitasking is easy with 16GB of RAM; Equipped with a blazing fast Core i5 2.00 GHz processor.
$304.99

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.