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

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

Mary-Kate Olsen
Release: 2025-01-17 12:07:10
Original
468 people have browsed it

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

C# takes a screenshot of the specified application window

In some cases, it is necessary to take a screenshot of a specific application or window rather than the entire screen. This is achieved through the PrintWindow Win32 API, which allows windows to be printed to the device context.

Code implementation

The following C# code demonstrates how to take a screenshot of a specified window:

<code class="language-csharp">// 导入所需的Win32 API
[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);

// 定义表示RECT结构的类
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

// 获取窗口句柄和尺寸
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();

// 现在您拥有了表示指定窗口截图的位图</code>
Copy after login

Other instructions

  • The PrintWindow function intercepts the client area of ​​the window, not other parts such as the border or menu.
  • If the window is partially visible, only the visible part is captured.
  • Captured screenshots can be saved to a file or displayed in an image viewer.

The above is the detailed content of How Can I Take a Screenshot of a Specific Application Window Using 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