如果您想知道用于菜单项的宽度,您可以:
-
使用GetMenuItemRect() 获取最后一个菜单项的屏幕坐标,然后将它们转换为父窗口内的客户端坐标。转换后的右边缘坐标将为您提供宽度:
HMENU hMenu = ::GetMenu(hWnd);
int count = ::GetMenuItemCount(hMenu);
RECT r;
if (::GetMenuItemRect(hWnd, hMenu, count-1, &r))
{
::MapWindowPoints(NULL, hWnd, (LPPOINT)&r, 2);
int nUsedWidth = r.right;
...
}
-
以上假设菜单从窗口客户区内的偏移量 0 开始。如果您不想依赖它,您可以改为获取第一个菜单项的 屏幕坐标,然后从最后一个菜单项的右边缘 屏幕坐标 中减去它菜单项:
HMENU hMenu = ::GetMenu(hWnd);
int count = ::GetMenuItemCount(hMenu);
RECT rFirst, rLast;
if (::GetMenuItemRect(hWnd, hMenu, 0, &rFirst) &&
::GetMenuItemRect(hWnd, hMenu, count-1, &rLast))
{
int nUsedWidth = rLast.right - rFirst.left;
...
}
无论哪种方式,如果您想知道不用于菜单项的宽度,只需获取菜单的总宽度并减去上面计算的宽度:
MENUBARINFO mbi = {0};
mbi.cbSize = sizeof(mbi);
if (::GetMenuBarInfo(hWnd, OBJID_MENU, 0, &mbi))
{
int nUsableWidth = (mbi.rcBar.right - mbi.rcBar.left) - nUsedWidth;
...
}
更新:如果客户区太小而无法在一行上显示它们,我没有意识到窗口的菜单可以垂直包装其项目。在这种情况下,您可能需要执行类似这样的操作来计算 nUsedWidth:
HMENU hMenu = ::GetMenu(hWnd);
int count = ::GetMenuItemCount(hMenu);
int nUsedWidth = 0;
RECT r;
for(int idx = 0; idx < count; ++idx)
{
if (::GetMenuItemRect(hWnd, hMenu, idx, &r))
{
::MapWindowPoints(NULL, hWnd, (LPPOINT)&r, 2);
if (r.right > nUsedWidth)
nUsedWidth = r.right;
}
}
...
或者:
HMENU hMenu = ::GetMenu(hWnd);
int count = ::GetMenuItemCount(hMenu);
int nUsedWidth = 0;
RECT rFirst, r;
if (::GetMenuItemRect(hWnd, hMenu, 0, &rFirst))
{
nUsedWidth = rFirst.right - rFirst.left;
for (int idx = 1; idx < count; ++idx)
{
if (::GetMenuItemRect(hWnd, hMenu, idx, &r))
{
int nWidth = r.right - rFirst.left;
if (nWidth > nUsedWidth)
nUsedWidth = nWidth;
}
}
}
...