Search code examples
mfchotkeys

Preventing a hotkey if modal popup windows are displayed


A few months ago here on StackOverflow someone encouraged me to do things properly and use hotkeys. As I result I followed their advice.

I have several hotkeys allocated in my Editor and I have just encountered an issue. Here is one of the hotkeys:

if (!RegisterHotKey(GetSafeHwnd(), hkEditor_WeekendMeeting, MOD_CONTROL | MOD_SHIFT, 0x57)) // W
    aryStrHotKeyErrors.Add(_T("Control + Shift + W"));

The hotkey event handler:

void CChristianLifeMinistryEditorDlg::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2)
{
    switch (nHotKeyId)
    {
    case hkEditor_WeekendMeeting:
        OnFilePublicTalk();
        break;
    default:
        CDialogEx::OnHotKey(nHotKeyId, nKey1, nKey2);
    }
}

I have removed out all the other hotkeys for clarity. OnFilePublicTalk displays a popup modal dialog:

void CChristianLifeMinistryEditorDlg::OnFilePublicTalk()
{
    CPublicTalkDlg dlgPublicTalk(this);

    if (m_pEntry != nullptr)
    {
        dlgPublicTalk.SetPublicTalkInfo(m_pEntry->GetPublicTalkInfo());
        dlgPublicTalk.SetCircuitVisitMode(m_iIncludeMode == kIncludeServiceTalk); // AJT v17.0.7
        if (dlgPublicTalk.DoModal() == IDOK)
        {
            m_pEntry->SetPublicTalkInfo(dlgPublicTalk.GetPublicTalkInfo());

            SetModified(true);
            UpdatePreview(m_iDateIndex);
            m_pHtmlPreview->Refresh2(REFRESH_COMPLETELY); // Ensure it has refreshed
        }
    }
}

The hotkey works fine. However, if I am inside another modal popup window in my editor at the time and accidently press the hotkey, up comes the window. I did not expect any of my hotkeys to function if popup windows are displayed.

How do I correct this?


Solution

  • I came up with this solution:

    void CChristianLifeMinistryEditorDlg::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2)
    {
        if (GetActiveWindow() != this)
        {
            CDialogEx::OnHotKey(nHotKeyId, nKey1, nKey2);
            return;
        }
    
        switch (nHotKeyId)
        {
        case hkEditor_WeekendMeeting:
            OnFilePublicTalk();
            break;
        default:
            CDialogEx::OnHotKey(nHotKeyId, nKey1, nKey2);
        }
    }
    

    I used GetActiveWindow. Was it the right way to resolve this?