如何在Windows中获取窗口的默认标题栏高度?

Jic*_*hao 2 windows winapi win32gui

我正在开发一个使用自绘标题栏的应用程序,它需要模仿系统默认标题栏.

那么如何才能获得Windows中超载窗口的默认标题栏高度?

Jic*_*hao 7

从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;
Run Code Online (Sandbox Code Playgroud)

PS:高度取决于dpi.


Sim*_*ier 5

一种解决方案是使用AdjustWindowRectEx 函数,该函数还计算其他窗口边框宽度,并允许窗口样式变化:

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

对于现代 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
Run Code Online (Sandbox Code Playgroud)