获取Win32 TreeView控件的宽度

时间:2011-02-24 09:51:46

标签: winapi user-interface treeview

Win32 TreeView控件没有内置消息/宏来获取其(可滚动)宽度,例如如果想设置TreeView的宽度,则不需要滚动条。

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

这是执行此操作的C函数:

int TreeView_GetWidth(HWND hTreeWnd)
{
    SCROLLINFO scrollInfo;
    SCROLLBARINFO scrollBarInfo;

    scrollInfo.cbSize = sizeof(scrollInfo);
    scrollInfo.fMask = SIF_RANGE;

    scrollBarInfo.cbSize = sizeof(scrollBarInfo);

    // To find the whole (scrollable) width of the tree control,
    // we determine the range of the scrollbar.
    // Unfortunately when a scrollbar isn't needed (and is invisible),
    // its range isn't zero (but rather 0 to 100),
    // so we need to specifically ignore it then.
    if (GetScrollInfo(hTreeWnd, SB_HORZ, &scrollInfo) &&
        GetScrollBarInfo(hTreeWnd, OBJID_HSCROLL, &scrollBarInfo))
    {
        // Only if the scrollbar is displayed
        if ((scrollBarInfo.rgstate[0] & STATE_SYSTEM_INVISIBLE) == 0)
        {
            int scrollBarWidth = GetSystemMetrics(SM_CXVSCROLL);
            // This is a hardcoded value to accomodate some extra pixels.
            // If you can find a cleaner way to account for them (e.g. through
            // some extra calls to GetSystemMetrics), please do so.
            // (Maybe less than 10 is also enough.)
            const int extra = 10;

            return (scrollInfo.nMax - scrollInfo.nMin) + scrollBarWidth + extra;
        }
    }

    return 0;
}