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>
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>
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!