How to Expand/Collapse TreeCtrl nodes by using Enter Key?

2 01 2009

You can see Tree Control, almost in every heavy windows applications. They are very convineant  method for organize things in hierarchy. But by default Tree control doesn’t support expand/collapse of its tree nodes by Enter key. Is there any way to do that?

Picture Courtesy – hawaiibonsai

Yes, you can! All you want to do is – Override PreTranslateMessage() in your dialog and handle all WM_KEYDOWN messages for your tree control. If, the key is VK_RETURN, i.e. enter key, then check whether the current selected node in TreeCtrl is expanded or collapsed and modify the key stroke as WM_ADD key or WM_SUBSTRACT key accordingly. The idea is, if you press +, then tree node expands and for – key, the tree node collapse – which is the default behavior of tree control. Well, have a look at the code snippet.

BOOL CRabbitDlg::PreTranslateMessage(MSG* pMsg)
    // Check whether its a keypress.
    if( pMsg->message == WM_KEYDOWN )
        // Check whether its for our tree control.
        UINT CtrlId = ::GetDlgCtrlID( pMsg->hwnd );
        if( CtrlId == IDC_TREECTRL )
            // Check whether its enter key.
            if( pMsg->wParam == VK_RETURN)
                // Check whether the currently selected item is
                HTREEITEM CurrentItem = m_TreeCtrl.GetSelectedItem();
                if( m_TreeCtrl.GetItemState( CurrentItem, TVIS_EXPANDED )
                        & TVIS_EXPANDED )
                    // Current Item is Expanded.
                    // So send - Key code to collapse it.
                    pMsg->wParam = VK_SUBTRACT;
                    // Current Item is Collapsed.
                    // So send + Key code to Expand it.
                    pMsg->wParam = VK_ADD;

    return CDialog::PreTranslateMessage(pMsg);

If you want the expand entire child nodes under a perticular node, then press * key. I used to use this techniqe to report performance bugs. 😉

Targeted Audience – Intermediate.