Capture screen of Window by handle
<p>I'm trying to capture only a specific Window in the desktop but I'm getting a mixed image, part of window and part desktop area.</p>

<p>What am I missing?</p>

<p>Here's my code:</p>

<pre><code>RECT rect = new RECT();

if (!SetForegroundWindow(handle))
    throw new Win32Exception(Marshal.GetLastWin32Error());

if (!GetWindowRect(handle, out rect))
    throw new Win32Exception(Marshal.GetLastWin32Error());

Thread.Sleep(500);

Rectangle windowSize = rect.ToRectangle();
Bitmap target = new Bitmap(windowSize.Width, windowSize.Height);
using (Graphics g = Graphics.FromImage(target))
{
    g.CopyFromScreen(0, 0, 0, 0, new Size(windowSize.Width, windowSize.Height));
}

target.Save("foo.png", System.Drawing.Imaging.ImageFormat.Png);
</code></pre>