简体   繁体   中英

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 在此输入图像描述

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: 在此输入图像描述

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 ie 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM