Windows:窗口位置X坐标不正确

时间:2019-06-13 11:56:15

标签: c++ winapi windows-10 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;
    }
}

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

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

我希望此SetWindowPos()调用可以将窗口完美地放置在屏幕的左上角,但是窗口和屏幕边框之间还留有一些空间(恰好8像素)。有没有办法确保自动考虑此水平偏移?这可能与笔记本电脑有关,那么如何使其表现出预期的效果?

1 个答案:

答案 0 :(得分:2)

根据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;
}

代码基于this帖子。我的机器上的返回值为7

相关问题