5

I am developing an application which employs a self-drawn titlebar, which needs to mimic the system default titlebar.

So how could I get the default titlebar height of an overloapped window in Windows?

jschroedl
  • 4,916
  • 3
  • 31
  • 46
Jichao
  • 40,341
  • 47
  • 125
  • 198

2 Answers2

12

Source code ported from 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: the height is dpi-dependent.

Jichao
  • 40,341
  • 47
  • 125
  • 198
  • 1
    Measuring the actual title bar size at different DPI scaling settings, it seems to be less straightforward than I would've expected (e.g. multiplying by `DPI/96.0f`). I've arrived at this: `std::ceil( ((GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYFRAME)) * dpi_scale) + GetSystemMetrics(SM_CXPADDEDBORDER) )` – melak47 Jun 07 '17 at 17:16
  • 1
    GetSystemMetricsForDpi – Charles Milette Jul 22 '19 at 00:51
5

One solution is to use the AdjustWindowRectEx function which also computes other window borders width, and allows for window style variations:

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

And for modern Windows (10+), there is the DPI-aware version:

// 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
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • This answer was very helpful. For more information about DPI, see a code sample from Microsoft on GitHub: https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/DPIAwarenessPerWindow/client/DpiAwarenessContext.cpp#L241 – kevinarpe Jan 01 '23 at 14:28