Problem with TVN_SELCHANGED on CTreeCtrl object
-
01-07-2019 - |
Question
I have tree control object created using CTreeCtrl MFC class. The tree control needs to support rename. When I left click on any of item in Tree the TVN_SELCHANGED event is called from which I can get the selected item of the tree as below : HTREEITEM h = m_moveListTree.GetSelectedItem(); CString s = m_moveListTree.GetItemText(h);
However when I rightclick on any item in tree I do not get any TVN_SELCHANGED event and hence my selected item still remains the same from left click event. This is causing following problem : 1)User leftclicks on item A 2)user right clicks on item B and says rename 3)Since the selected item is still A the rename is applying for item A.
Please help in solving problem.
-Praveen
Solution
I created my own MFC like home grown C++ GUI library on top of the Win32 API and looking at my code, this is how it handles that situation:
LRESULT xTreeCtrl::onRightClick(NMHDR *)
{
xPoint pt;
//-- get the cursor at the time the mesage was posted
DWORD dwPos = ::GetMessagePos();
pt.x = GET_X_LPARAM(dwPos);
pt.y = GET_Y_LPARAM (dwPos);
//-- now convert to window co-ordinates
pt.toWindow(this);
//-- check for a hit
HTREEITEM hItem = this->hitTest(pt);
//-- select any item that was hit
if ((int)hItem != -1) this->select(hItem);
//-- leave the rest to default processing
return 0;
}
I suspect if you do something similar in the MFC right click or right button down events that will fix the problem.
NOTE: The onRightClick code above is nothing more than the handler for the WM_NOTIFY, NM_RCLICK message.
OTHER TIPS
This behaviour is by design -- right-clicking doesn't move the selection.
For what you want, turn on the TVS_EDITLABELS style on the tree view. Then you handle the TVN_BEGINLABELEDIT and TVN_ENDLABELEDIT notifications.
Not sure how you popup the context menu, but you can use HitTest() to get from a point to a tree item. So you might use this in your right click handler.
Don't forget that the context menu can also be activated by a key on reasonable modern keyboards. Then you probably want to use the selected item as target.