Windows:获取窗口标题栏的高度

Bul*_*aza 6 c++ windows winapi

我试图获取 Windows 上特定窗口的标题栏的高度。你可以用记事本复制它。我正在使用 C++,但我在网上找到的所有代码都没有产生正确的结果。例如,Screenpresso我测量31了窗口栏高度的像素。

我尝试的功能如下:

TitleBarHeight.h

#pragma once

#include <windows.h>

inline int get_title_bar_thickness_1(const HWND window_handle)
{
    RECT window_rectangle, client_rectangle;
    GetWindowRect(window_handle, &window_rectangle);
    GetClientRect(window_handle, &client_rectangle);
    return window_rectangle.bottom - window_rectangle.top -
        (client_rectangle.bottom - client_rectangle.top);
}

inline int get_title_bar_thickness_2(const HWND window_handle)
{
    RECT window_rectangle, client_rectangle;
    GetWindowRect(window_handle, &window_rectangle);
    GetClientRect(window_handle, &client_rectangle);
    return (window_rectangle.right - window_rectangle.left - client_rectangle.right) / 2;
}
Run Code Online (Sandbox Code Playgroud)

结果:

auto window_handle = FindWindow("Notepad", nullptr);
auto a = get_title_bar_thickness_1(window_handle); // 59
auto b = get_title_bar_thickness_2(window_handle); // 8
auto c = GetSystemMetrics(SM_CXSIZEFRAME); // 4
auto d = GetSystemMetrics(SM_CYCAPTION); // 23
Run Code Online (Sandbox Code Playgroud)

获取系统指标GetSystemMetrics()不起作用,因为窗口显然可以具有不同的标题栏高度,并且窗口句柄没有参数。

我怎样才能真正得到结果31

Dan*_*Sęk 4

假设您没有菜单栏,您可以将点从客户端坐标系映射到屏幕一

RECT wrect;
GetWindowRect( hwnd, &wrect );
RECT crect;
GetClientRect( hwnd, &crect );
POINT lefttop = { crect.left, crect.top }; // Practicaly both are 0
ClientToScreen( hwnd, &lefttop );
POINT rightbottom = { crect.right, crect.bottom };
ClientToScreen( hwnd, &rightbottom );

int left_border = lefttop.x - wrect.left; // Windows 10: includes transparent part
int right_border = wrect.right - rightbottom.x; // As above
int bottom_border = wrect.bottom - rightbottom.y; // As above
int top_border_with_title_bar = lefttop.y - wrect.top; // There is no transparent part
Run Code Online (Sandbox Code Playgroud)

有 8、8、8 和 31 像素(96DPI 又名 100% 缩放设置)

您还应该考虑 DPI 感知模式。尤其GetSystemMetrics棘手的是,它会记住应用程序启动时系统 DPI 的状态。