Windows: Window位置X坐标不准确

Windows: Window position X coordinate not accurate

我想获取 window (the client area) 的(准确)屏幕 XY 坐标。我的问题是我必须定义一个水平移动,它必须添加到 X 坐标上才能得到正确的结果:

#include <windows.h>

inline int get_title_bar_thickness(const HWND window_handle)
{
    RECT window_rectangle, client_rectangle;
    GetWindowRect(window_handle, &window_rectangle);
    GetClientRect(window_handle, &client_rectangle);
    const int height = window_rectangle.bottom - window_rectangle.top -
        (client_rectangle.bottom - client_rectangle.top);
    const int width = window_rectangle.right - window_rectangle.left -
        (client_rectangle.right - client_rectangle.left);
    return height - width / 2;
}

#define HORIZONTAL_SHIFT 8

/**
 * Gets the window position of the window handle
 * excluding the title bar and populates the x and y coordinates
 */
inline void get_window_position(const HWND window_handle, int* x, int* y)
{
    RECT rectangle;
    const auto window_rectangle = GetWindowRect(window_handle, &rectangle);
    const auto title_bar_thickness = get_title_bar_thickness(window_handle);
    if (window_rectangle)
    {
        *x = rectangle.left + HORIZONTAL_SHIFT;
        *y = rectangle.top + title_bar_thickness;
    }
}

可以通过以编程方式移动 window 来观察问题:

const auto window_handle = FindWindow(nullptr, "Command Prompt");
SetWindowPos(window_handle, nullptr, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER);

我希望这个 SetWindowPos() 调用能够将 window 完美地放置在我屏幕的左上角,但是在 window 和 window 之间还剩下一些 space屏幕边框(恰好 8 个像素)。有没有办法确保自动考虑这种水平偏移?这可能与笔记本电脑有关,那么如何使其按预期运行?

Castorix所述,可以检索水平偏移。

#include <dwmapi.h>

#pragma comment(lib, "dwmapi.lib")

inline int get_horizontal_shift(const HWND window_handle)
{
    RECT window_rectangle, frame_rectangle;
    GetWindowRect(window_handle, &window_rectangle);
    DwmGetWindowAttribute(window_handle,
                         DWMWA_EXTENDED_FRAME_BOUNDS, &frame_rectangle, sizeof(RECT));

    return frame_rectangle.left - window_rectangle.left;
}

代码基于post。 return 值在我的机器上是 7