How to Expand/Collapse TreeCtrl nodes by using Enter Key?
![]()
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;
}
else
{
// 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 particular node, then press * key. I used to use this techniqe to report performance bugs.
![]()
Targeted Audience – Intermediate.
This entry was posted by Jijo Raj on January 2, 2009 at 11:23 pm, and is filed under Codeproject, MFC. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site.
[...] How to Expand/Collapse TreeCtrl nodes by using Enter Key? WordPress 3.0 jQuery: Enhance your WordPress website with the captivating effects of jQuery [...]