How to prevent an MFC dialog from handling the enter and escape keys and not passing it on

10,934

Solution 1

Remove OnOK() and OnCancel(); PreTransateMessage is enough after considering VK_ESCAPE.

Why don't you use:

m_ctrlFlex->SendMessage(WM_KEYDOWN, VK_RETURN, 0)

instead of

m_ctrlFlex->OnReturnKeyPressed();

in your implementation of PreTranslateMessage ?

Solution 2

MFC command buttons can respond to events even if they do not have the focus.

Have you tried trapping the OnClicked event and OnOk to return nothing?

Example: trap OnClick...

   void CMyDialog::OnClickedMyOK()
   {
      CDialog::OnOK();
   }

Then do a no-op in the OnOk()

void CMyDialog::OnOK()
{
}

This should stop the enter key from being processed.

Share:
10,934
Kurt
Author by

Kurt

Updated on June 17, 2022

Comments

  • Kurt
    Kurt about 2 years

    we have a C++ application that hosts a flex application in a MFC dialog. Everything works fine, all button pushes etc are passed directly on to flex with no problem at all, except the enter and escape keys, which immediately closes the dialog.

    We can trap the enter key, by implementing PreTranslateMessage() or OnOK() and impede the window closing behavior, but we still have the problem of passing these enter key pushes on to the hosted flex app further.

    There is no "default" button on the form or anything like that, perhaps MFC is linking the enter key to the close button in the title bar behind the scenes or something.

    Does anyone have any ideas how we can stop MFC from treating the enter key from being a special case.

    Thanks a lot for any hints.

    Edit: Here is PreTranslateMessage() that mmonem requested.

    BOOL CFlexDialog::PreTranslateMessage(MSG* pMsg)
    {
      if ((pMsg->message == WM_KEYDOWN))
      {
        if (pMsg->wParam == VK_RETURN)
        {
          m_ctrlFlex->OnReturnKeyPressed();
          return TRUE;
        }
      }
      return __super::PreTranslateMessage(pMsg);
    }
    

    But it is not a suitable solution, calling a method in the flex app like that, as it makes life too difficult for the flex developer, it means he must write a special version implementing the return key behavior for every control.

    We just want MFC to treat the return and escape keys like every other key.