Wednesday, August 27, 2008

CTreeCtrl and Checkboxes

While working with CTreeCtrl with checkboxes, I came across these 2 issues

1. You would have set TVS_CHECKBOXES in the .rc file. Then during InitDialog, if
m_myTreeVar.SetCheck( hTreeWnd, TRUE)

is called, it will not work as expected. But, when the same line is called anywhere else later, it will work. To workaround this issue, the following two lines need to be added to simulate a removal/addition of the checkboxes flag at the beginning of InitDialog

m_myTree.ModifyStyle( TVS_CHECKBOXES, 0 );
m_myTree.ModifyStyle( 0, TVS_CHECKBOXES );

2. With the CTreeCtrl, when trying to get the handle of a "clicked" item using hittest, I fell on an issue that it was returning the handle of the NEXT item on the list and not the one which i clicked. The code is as below
 DWORD pos = GetMessagePos();
CPoint pt(LOWORD(pos), HIWORD(pos));
ScreenToClient(&pt);
UINT uFlags = 0;
HTREEITEM hItem = m_MainTree.HitTest(pt, &uFlags);


The above code returned the handle of the next list item from the one clicked. To fix the same, I just modified the "ScreenToClient" as below
m_myTree.ScreenToClient(&pt); 

and Voila!!! it worked!