Does This HTREEITEM Belong To This TreeView Control?

a_unique_name 401 Reputation points
2024-03-30T05:17:42.5433333+00:00

Hello Folks:

Developing on Win 10 Pro, Visual Studio 2022 Version 17.9.4 ( updated yesterday), C++, Win32 no MFC.

TL,DR: Is there a way to see if an HTREEITEM belongs to a TreeView?

My treeview's customdraw notification is being passed an HTREEITEM that makes no sense, 0xCCCCCCCC.

The code attempts to use this HTREEITEM in a SendMessage(..., TVM_GETITEM, ..., ...) to the TreeView and the program fails spectacularly. It consistently fails in the code I use to subclass the TreeView control.

I have a lot of work to do in order to find the cause of the problem, but I'm wondering if there is a safe way to see if a HTREEITEM belongs to a TreeView.

Thanks

Larry

Windows development | Windows API - Win32
Developer technologies | C++
Developer technologies | Visual Studio | Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2024-03-30T06:50:13.5333333+00:00

    If it is always 0xCCCCCCCC, use if(item == (HTREEITEM)0xCCCCCCCC).... Or try this helper function:

    bool IsValid( HWND tree, HTREEITEM item, HTREEITEM parent = NULL )
    {
        HTREEITEM t = (HTREEITEM)SendMessage( tree, TVM_GETNEXTITEM, parent == NULL ? TVGN_ROOT : TVGN_CHILD, (LPARAM)parent );
    
        for( ; t != NULL;)
        {
            if( t == item ) return true;
            if( IsValid( tree, item, t ) ) return true;
    
            t = (HTREEITEM)SendMessage( tree, TVM_GETNEXTITEM, TVGN_NEXT, (LPARAM)t );
        }
    
        return false;
    }
    

    The call IsValid( tree, (HTREEITEM)0xCCCCCCCC ) should return false.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. RLWA32 49,636 Reputation points
    2024-03-30T08:31:52.8766667+00:00

    In debug builds the VC++ compiler will store sentinel values in uninitialized variables. Variables allocated on the heap are filled with 0xCD and stack variables are filled with 0xCC.

    If your HTREEITEM variable contains 0xCCCCCCCC that would indicate that you are working with an uninitialized variable that is an invalid HTREEITEM.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.