我试图获取 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/