Capture entire window with winapi

407 views Asked by At

I am using winapi to capture the window of opened software applications in Java. This function below captures the window of the software application and returns the image.

public static BufferedImage capture(HWND hWnd) {
   HDC hdcWindow = User32.INSTANCE.GetDC(hWnd);
   HDC hdcMemDC = GDI32.INSTANCE.CreateCompatibleDC(hdcWindow);
   RECT bounds = new RECT();
   RECT bounds1 = new RECT();
   User32Extra.INSTANCE.GetWindowRect(hWnd, bounds);
   User32Extra.INSTANCE.GetClientRect(hWnd, bounds1);

   int extraGap = (bounds.right-bounds.left-bounds1.right);
   int width = bounds.right-bounds.left-extraGap;
   int height = bounds.bottom-bounds.top-extraGap ;
   HBITMAP hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcWindow, width, height);

   HANDLE hOld = GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap);
   GDI32Extra.INSTANCE.BitBlt(hdcMemDC,0, 0, width, height, hdcWindow, bounds.left+bounds1.right-bounds.right+extraGap, bounds.top+bounds1.bottom-bounds.bottom+extraGap, WinGDIExtra.MERGECOPY);
   GDI32.INSTANCE.SelectObject(hdcMemDC, hOld);

   BITMAPINFO bmi = new BITMAPINFO();
   bmi.bmiHeader.biWidth = width;
   bmi.bmiHeader.biHeight = -height;
   bmi.bmiHeader.biPlanes = 1;
   bmi.bmiHeader.biBitCount = 32;
   bmi.bmiHeader.biCompression = WinGDI.BI_RGB;
   Memory buffer = new Memory(width * height * 4);
   GDI32.INSTANCE.GetDIBits(hdcWindow, hBitmap, 0, height, buffer, bmi, WinGDI.DIB_RGB_COLORS);

   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   image.setRGB(0, 0, width, height, buffer.getIntArray(0, width * height), 0, width);

   System.out.println(GDI32.INSTANCE.DeleteObject(hBitmap));
   System.out.println(GDI32.INSTANCE.DeleteObject(hdcMemDC));
   System.out.println(User32.INSTANCE.ReleaseDC(hWnd, hdcWindow));

   return image;
} 

The image captured has some errors like:-

  1. This is the image of Flash Builder window with Eclipse Title Bar.

    Flash Builder Image with Eclipse title Bar

  2. This is the image of Chrome Browser without Window buttons.

    Chrome window without window buttons

  3. This is the image of file browser with Eclipse title bar.

    File Browser window with

  4. Sometimes the title bar is not captured in the image.

Do you have any idea why, and how I could solve this problem? Anything wrong in my code?

0

There are 0 answers