BullyWiiPlaza
BullyWiiPlaza

Reputation: 19223

Windows: Window position X coordinate not accurate

I want to get the (accurate) on-screen X and Y coordinates of a window (the client area). My problem is that I have to define a horizontal shift which has to be added onto the X coordinate to get the correct result:

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

The issue can be observed by moving the window programmatically:

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

I would expect this SetWindowPos() call to perfectly place the window into the upper left corner of my screen but there is some space left between the window and the screen border (exactly 8 pixels). Is there a way to assure that this horizontal offset is automatically considered? This might be related to laptops so how to make this behave as expected?

Upvotes: 0

Views: 1146

Answers (1)

BullyWiiPlaza
BullyWiiPlaza

Reputation: 19223

As commented by Castorix, the horizontal shift can be retrieved.

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

The code is based on this post. The return value is 7 on my machine.

Upvotes: 3

Related Questions