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

标签 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;
}

结果:

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

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

如何才能真正得到31的结果?

最佳答案

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

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

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

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

关于c++ - Windows:获取窗口标题栏的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56549853/

相关文章:

winapi - 为什么我的 Windows 应用程序按照规则不应获得焦点?

c++ - 比较两个 QColor 对象的颜色

c++ - 如何正确使用命名空间避免名称冲突?

c++ - 基于 ffmpeg 的多线程 C++ 应用程序解码失败

windows - 将文件复制到所有用户的启动文件夹

c++ - For-Loop a "Empty"Vector with negative iterator?

c++ - 应该使用 Cocos2d 还是在 C 中创建自己的代码

c++ - 如何在 Windows 中获取屏幕比例?

c - fputs(text, filePtr) 仅从 SendMessage 返回 LPARAM 的第一个字符,而不是整个字符串

c++ - EnterSynchronizationBarrier卡在Windows 8中