Unable to capture a snapshot of a specific window in WinForms. I have tried to capture the WinForms window specifically. However, it captures the snapshot along with portions of other windows.
I have tried to capture the WinForms window using the GetForegroundWindow() function from the User32 DLL to find the handle, and then I have used the Graphics.CopyFromScreen method to capture the content of the window specified by the windowHandle. However, it captures the snapshot along with portions of other windows.
internal BitmapSource TakeScreenSnapshot(IntPtr windowHandle)
{
User32.RECT bounds = GetWindowBounds(windowHandle);
Thickness padding = GetWindowClientArea(windowHandle);
using (Bitmap bmp = new Bitmap((int)bounds.Width, (int)bounds.Height))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen((int)bounds.left, (int)bounds.top, 0, 0, bmp.Size);
}
IntPtr hBitmap = bmp.GetHbitmap();
try
{
return Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
finally
{
User32.DeleteObject(hBitmap);
}
}
}