Home >Backend Development >C++ >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>
Other instructions
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!