locked
Visual Studio MFC dialog application , Press ESC to exit app RRS feed

  • Question

  • I created a dialog application in Visual Studio MFC.

    I run the exe file and press "ESC" , the app will be closed.

    Any way to don't close app when user press "ESC"?

    Thursday, August 13, 2020 7:57 AM

Answers

  • Hi,

    Thank you for posting here.

    >>Any way to don't close app when user press "ESC"?

    I suggest you could try to override the PreTranslateMessage notification and block all VK_ESCAPE messages of WM_KEYDOWN.

    Here is my code:

    BOOL CMFCApplication85Dlg::PreTranslateMessage(MSG* pMsg)
    {
        if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE)     return   TRUE;
       
        else
    
        return CDialogEx::PreTranslateMessage(pMsg);
    }

    Best Regards,

    Jeanine Zhang


    "Visual c++" forum will be migrating to a new home on Microsoft Q&A !
    We invite you to post new questions in the "Developing Universal Windows apps" forum’s new home on Microsoft Q&A !
    For more information, please refer to the sticky post.

    • Proposed as answer by Guido Franzke Thursday, August 13, 2020 9:21 AM
    • Marked as answer by gsegria Thursday, August 13, 2020 10:27 AM
    Thursday, August 13, 2020 9:19 AM

All replies

  • Hi,

    Thank you for posting here.

    >>Any way to don't close app when user press "ESC"?

    I suggest you could try to override the PreTranslateMessage notification and block all VK_ESCAPE messages of WM_KEYDOWN.

    Here is my code:

    BOOL CMFCApplication85Dlg::PreTranslateMessage(MSG* pMsg)
    {
        if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE)     return   TRUE;
       
        else
    
        return CDialogEx::PreTranslateMessage(pMsg);
    }

    Best Regards,

    Jeanine Zhang


    "Visual c++" forum will be migrating to a new home on Microsoft Q&A !
    We invite you to post new questions in the "Developing Universal Windows apps" forum’s new home on Microsoft Q&A !
    For more information, please refer to the sticky post.

    • Proposed as answer by Guido Franzke Thursday, August 13, 2020 9:21 AM
    • Marked as answer by gsegria Thursday, August 13, 2020 10:27 AM
    Thursday, August 13, 2020 9:19 AM
  • If all messages are blocked then any control in the dialog that actually uses the ESC key will lose functionality.  For example, pressing ESC to close a combobox dropdown list will no longer function.

    Add a test to the PreTranslateMessage override to only handle messages for the dialog box window -

    if (pMsg->hwnd == m_hWnd && pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE)


    • Edited by RLWA32 Thursday, August 13, 2020 9:33 AM
    Thursday, August 13, 2020 9:33 AM