使用 Java 在 Windows 中拍摄前景应用程序屏幕截图,没有额外的边缘

Take foreground application screenshot in Windows using Java without extra edges

我可以使用下面的代码截取前景图像

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);
}

我得到如下的前景截图

如果您注意到,屏幕截图在 window 的边框处有一些额外的图像。

我不想在屏幕截图中添加额外的图像部分。

是否有可能以某种方式操纵

User32.INSTANCE.GetForegroundWindow()

这样我就可以得到没有多余部分的截图?

我觉得 link 中的答案应该有效。 WinApi中的GetClientRect和GetWindowRect有什么区别?

但是当我用 GetClientRect 替换 GetWindowRect 时,我得到以下屏幕截图:

理想情况下,我应该只获得前台应用程序的屏幕截图。

编辑: Daniel Widdis 好心地为我找到了一个类似的问题:

这有一个可能的答案,即在 Windows 10 中获取边框粗细并调整此粗细以获得我想要的屏幕截图。但是这个答案使用 DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, &frame, sizeof(RECT)); 这可能是 C 代码。

如果我能在 Java 中找到如何找到边框粗细,它就会解决我的问题。

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

这是一个相对坐标系。

您还应该调用 ClientToScreen 将客户端坐标转换为屏幕坐标。

注意ClientToScreen只接受POINT的参数(不是RECT),可以找到POINT class here.

编辑:

GetWindowRect 将获得 "extra" 尺寸。但是,GetClientRect 确实不包括它(以及其他额外信息,如标题栏、window 边框等)。