3

I am on windows XP and I am trying to captrue a window.

But when I capture a window, I get the window title (Name & Icon) but the entire content of the window is black.

When trying to save the image, the whole image is transparent.

This is my code :

    [DllImport("User32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr handle, ref Rectangle rect);

    public void CaptureWindow(IntPtr handle)
    {
        Rectangle rect = new Rectangle();
        GetWindowRect(handle, ref rect);
        rect.Width = rect.Width - rect.X;
        rect.Height = rect.Height - rect.Y;
        try
        {
            Bitmap bmp = new Bitmap(rect.Width, rect.Height);
            Graphics memoryGraphics = Graphics.FromImage(bmp);
            IntPtr hdc = memoryGraphics.GetHdc();
            PrintWindow(handle, hdc, 0);
            ResultsPB.Image = bmp;
            memoryGraphics.ReleaseHdc(hdc);
        }
        catch (Exception)
        {
            throw;
        }
    }
user779444
  • 1,365
  • 4
  • 21
  • 38
  • i would recommand bitblt http://pinvoke.net/default.aspx/gdi32/BitBlt.html – Wowa Jul 26 '11 at 08:19
  • Nice but I need it for a game and I can recall that PrintWindow works for games (in XP). I guess I just need the proper code for PrintWindow. I can't use your method because GetWindowDC() returns null at the game I'm trying it in. – user779444 Jul 26 '11 at 08:56
  • The game probably uses DirectX or OpenGL. To capture these screens you have to capture the screen with DirectX/OpenGL. – Wowa Jul 26 '11 at 09:50
  • Well, How do I do that? (And I'm not sure it's the way to go since I can even capture it using printscreen) – user779444 Jul 26 '11 at 10:41

1 Answers1

3

Look at C# Capturing Direct 3D Screen. Print screen captures the visible area, not a handle.

DirectX and OpenGL draw directly via hardware. With PrintScreen you can only capture handle screen which are drawn managed by Windows.

If you only need the visible area use Graphics.CaptureFromScreen.

I've tried BitBlt and PrintScreen with an OpenGL demo from http://magnum.dimajix.de/download/demos.shtml without success. PrintScreen only returned a blank bitmap and BitBlt return an old capture(probably from the first and only WM_PAINT message).

Just try to start your game and listen to it's window-messages. You will see there is no WM_PAINT message. So Windows doesn't even know if there has anything changed.

Community
  • 1
  • 1
Wowa
  • 1,791
  • 1
  • 14
  • 24