Search code examples
javawinapijna

Take foreground application screenshot in Windows using Java without extra edges


I am able to take screenshot of foreground image using below code

void startScreencapture(){
    RECT dimensionsOfWindow = new RECT();
    User32.INSTANCE.GetWindowRect(User32.INSTANCE.GetForegroundWindow(), dimensionsOfWindow );//now in the dimensionsOfWindow you have the dimensions
    Robot robot = new Robot();
    buf = robot.createScreenCapture( dimensionsOfWindow.toRectangle() );
}

public interface User32 extends StdCallLibrary {
    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
    HWND GetForegroundWindow();  // add this
    int GetWindowTextA(PointerType hWnd, byte[] lpString, int nMaxCount);
    public boolean GetWindowRect(HWND hWnd, RECT rect);
}

I am getting foreground screenshots like below enter image description here

If you notice, the screenshot has some extra image at the border of the window.

I do not want extra image part with my screenshot.

Is it possible to somehow manipulate

User32.INSTANCE.GetForegroundWindow()

so that I get the screenshot without the extra part?

I feel like answer in this link should work. What is the difference between GetClientRect and GetWindowRect in WinApi?

But when I replace GetWindowRect with GetClientRect I get below screenshot: enter image description here

Ideally I should have got screenshot of only the foreground application.

Edit: Daniel Widdis kindly found a similar question for me: getwindowrect-returns-a-size-including-invisible-borders

This has a possible answer i.e. get the border thickness in Windows 10 and adjust this thickness to get the screenshot I want. But this answer uses DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, &frame, sizeof(RECT)); which is possibly C code.

If I can find how to find border thickness in Java, it would solve my problem.


Solution

  • GetClientRect:

    The client coordinates specify the upper-left and lower-right corners of the client area. Because client coordinates are relative to the upper-left corner of a window's client area, the coordinates of the upper-left corner are (0,0).

    This is a relative coordinate system.

    You should also call the ClientToScreen to convert the Client coordinate to screen coordinate.

    Notice that ClientToScreen only receive the parameter of POINT(not a RECT), and you can find the POINT class here.

    EDIT:

    GetWindowRect will get a "extra" size. However, GetClientRect does exactly not include it(and other extra information like title bar, window border, etc).