I have successfully gotten PrintWindow
to work in C++, but when I try to do it in C#, I get back a bitmap with null data. Using VS 2012 Pro, on .NET 4.0. Here is my code:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
[DllImport("user32.dll")]
public static extern ushort getLastError();
static int count = 0;
public Bitmap getWindow(IntPtr windowHandle)
{
RECT rect;
Window.GetWindowRect(windowHandle, out rect);
Console.WriteLine(rect.X);
Console.WriteLine(rect.Y);
Console.WriteLine(rect.Width);
Console.WriteLine(rect.Height);
Console.WriteLine();
Bitmap bmp = new Bitmap(rect.Width, rect.Height);
Graphics gfxBmp = Graphics.FromImage(bmp);
IntPtr hdcBitmap = gfxBmp.GetHdc();
bool success = PrintWindow(windowHandle, hdcBitmap, 0);
if (!success)
{
Console.WriteLine("Error copying image");
Console.WriteLine(getLastError());
}
bmp.Save("image_" + count++ + ".bmp");
gfxBmp.ReleaseHdc(hdcBitmap);
gfxBmp.Dispose();
return bmp;
}
Here is the output:
182
182
664
533
No error message printed and it looks like the handle is valid since the RECT bounds are correct. Following this example I got it working in C++ with the calculator program, but the same code with the calculator doesn't work in C#.
I need it to work in C#.