Handling ESC and Return Keys While Editing a Label

When I first implemented the tree view control and tried editing a label, the only way I could finish editing was to click elsewhere. MFC has been designed in such a way that the parent window gets a chance at the messages using the PreTranslateMessage() virtual function. If the parent window is a CDialog or a CFormView, the ESC and the return key are handled by the parent and does not reach the control. To allow our control to process some important messages we need to override the PreTranslateMessage() function. In our code below, we also also allow the control key combinations to go through to the control. This allows copy, cut and paste using the control key combinations.


BOOL CTreeCtrlX::PreTranslateMessage(MSG* pMsg)
{
if( pMsg->message == WM_KEYDOWN )
{
// When an item is being edited make sure the edit control
// receives certain important key strokes
if( GetEditControl()
(pMsg->wParam == VK_RETURN
|| pMsg->wParam == VK_DELETE
|| pMsg->wParam == VK_ESCAPE
|| GetKeyState( VK_CONTROL)
)
)
{
::TranslateMessage(pMsg);
::DispatchMessage(pMsg);
return TRUE; // DO NOT process further
}
}

return CTreeCtrl::PreTranslateMessage(pMsg);

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read