如何获取Windows中window的默认标题栏高度?

How to get the default caption bar height of a window in Windows?

我正在开发一个使用 self-drawn 标题栏的应用程序,它需要模仿系统默认的标题栏。

那么我怎样才能在 Windows 中获得重叠 window 的默认标题栏高度?

从 Firefox 移植的源代码:

// mCaptionHeight is the default size of the NC area at
// the top of the window. If the window has a caption,
// the size is calculated as the sum of:
//      SM_CYFRAME        - The thickness of the sizing border
//                          around a resizable window
//      SM_CXPADDEDBORDER - The amount of border padding
//                          for captioned windows
//      SM_CYCAPTION      - The height of the caption area
//
// If the window does not have a caption, mCaptionHeight will be equal to
// `GetSystemMetrics(SM_CYFRAME)`
int height = (GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CYCAPTION) +
    GetSystemMetrics(SM_CXPADDEDBORDER));
return height;

PS: 高度与 dpi 相关。

一种解决方案是使用 AdjustWindowRectEx function,它还计算其他 window 边框宽度,并允许 window 样式变化:

RECT rcFrame = { 0 };
AdjustWindowRectEx(&rcFrame, WS_OVERLAPPEDWINDOW, FALSE, 0);
// abs(rcFrame.top) will contain the caption bar height

对于现代 Windows (10+),有 DPI 感知版本:

// get DPI from somewhere, for example from the GetDpiForWindow function
const UINT dpi = GetDpiForWindow(myHwnd);
...
RECT rcFrame = { 0 };
AdjustWindowRectExForDpi(&rcFrame, WS_OVERLAPPEDWINDOW, FALSE, 0, dpi);
// abs(rcFrame.top) will contain the caption bar height