Search code examples
cwinapitreeviewcommon-controls

Creating a simple tree view using Common Controls in C


So I was trying to create a simple tree view using the Win32 API and CommnoControls. I've created a simple window, and in its WM_CREATE event, I've done the following:

HWND treeView = CreateWindowA(WC_TREEVIEWA, NULL, WS_VISIBLE | WS_CHILD, 10, 10,
        200, 500, window->info, (HMENU)1, GetModuleHandleA(NULL), NULL);

TVITEMA item = {0};
item.pszText = "My Item";

TVINSERTSTRUCTA insertStruct = {0};
insertStruct.hParent = NULL;
insertStruct.hInsertAfter = TVI_LAST;
insertStruct.item = item;
SendMessageA(treeView, TVM_INSERTITEMA, 0, &insertStruct);

The tree view does appear on the window, however the item (My Item) doesn't appear in it.

Is there anything else I need to do in order for it to appear? Maybe initialize something else? I tried to look in CommonControl's documentation but I didn't find anything else that would make sence to use... What am I doing wrong here?


Solution

  • Windows does not know that you provided text for the item because you failed to include TVIF_TEXT in the items mask member:

    HWND treeView = CreateWindowA(WC_TREEVIEWA, NULL, WS_VISIBLE | WS_CHILD | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT, 10, 10,
            200, 500, window->info, (HMENU)1, GetModuleHandleA(NULL), NULL);
    
    
    HTREEITEM hItem;
    TVINSERTSTRUCTA insertStruct = {0};
    TVITEMA*pItem = &insertStruct.item;
    insertStruct.hParent = NULL;
    insertStruct.hInsertAfter = TVI_ROOT;
    
    pItem->mask = TVIF_TEXT;
    pItem->pszText = "My Item";
    hItem = (HTREEITEM) SendMessageA(treeView, TVM_INSERTITEMA, 0, (LPARAM) &insertStruct);
    
    if (hItem)
    {
        insertStruct.hParent = hItem;
        pItem->pszText = "A Child";
        hItem = (HTREEITEM) SendMessageA(treeView, TVM_INSERTITEMA, 0, (LPARAM) &insertStruct);
        if (hItem) SendMessage(treeView, TVM_ENSUREVISIBLE, 0, (LPARAM) hItem);
    }
    

    Use the line and button TVS_* styles to control how items are displayed.