Home > Backend Development > C++ > How Can I Take a Screenshot of a Specific Application in C#?

How Can I Take a Screenshot of a Specific Application in C#?

Susan Sarandon
Release: 2025-01-17 11:56:09
Original
885 people have browsed it

How Can I Take a Screenshot of a Specific Application in C#?

C# takes screenshots of specified applications

Taking a screenshot of the entire screen is easy using Graphics.CopyFromScreen(). However, a more complex need is to take screenshots of only a specific application.

Use the PrintWindow function

The solution lies in using the PrintWindow Win32 API. It can capture the window bitmap even if the window is obscured or not on the screen. The following code demonstrates how to do this:

<code class="language-csharp">[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);

public static Bitmap PrintWindow(IntPtr hwnd) {
    RECT rc;
    GetWindowRect(hwnd, out rc);

    Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
    Graphics gfxBmp = Graphics.FromImage(bmp);
    IntPtr hdcBitmap = gfxBmp.GetHdc();

    PrintWindow(hwnd, hdcBitmap, 0);

    gfxBmp.ReleaseHdc(hdcBitmap);
    gfxBmp.Dispose();

    return bmp;
}</code>
Copy after login

The above code snippet requires the following classes to define the RECT structure:

<code class="language-csharp">[StructLayout(LayoutKind.Sequential)]
public struct RECT {
    private int _Left;
    private int _Top;
    private int _Right;
    private int _Bottom;
    // ... RECT 结构体的其余代码 ...
}</code>
Copy after login

With these code snippets, you can easily take a screenshot of the target application window by getting its handle. Just replace hwnd in the PrintWindow method with the handle of your desired application window.

The above is the detailed content of How Can I Take a Screenshot of a Specific Application in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template