Hungry Mind , Blog about everything in IT - C#, Java, C++, .NET, Windows, WinAPI, ...

How to prevent MFC dialog closing on Enter and Escape keys

In this article I explain how to prevent an MFC dialog from handling the Enter and Escape keys and not pass it on. With all required details for you to completely understand why does it work the way it does. There are several possible solutions, so you can choose the most suitable one.

The problem is the following: you have a dialog, no matter - top level window or just a child container; you press Escape or Enter keys - the dialog disappears, even if there are no OK and Cancel buttons on the dialog. It's very funny seeing a child dialog drops out it's parent.

Let's see why this happens:

OrderXMLReaderShell.exe!CFilterEditorDlgBase::OnCancel()  Line 61 C++
  mfc100ud.dll!_AfxDispatchCmdMsg(CCmdTarget * pTarget, unsigned int nID, int nCode, void (void)* pfn, void * pExtra, unsigned int nSig, AFX_CMDHANDLERINFO * pHandlerInfo)  Line 82 C++
  mfc100ud.dll!CCmdTarget::OnCmdMsg(unsigned int nID, int nCode, void * pExtra, AFX_CMDHANDLERINFO * pHandlerInfo)  Line 381 + 0x27 bytes C++
  mfc100ud.dll!CDialog::OnCmdMsg(unsigned int nID, int nCode, void * pExtra, AFX_CMDHANDLERINFO * pHandlerInfo)  Line 87 + 0x18 bytes C++
  mfc100ud.dll!CWnd::OnCommand(unsigned int wParam, long lParam)  Line 2729 C++
  mfc100ud.dll!CWnd::OnWndMsg(unsigned int message, unsigned int wParam, long lParam, long * pResult)  Line 2101 + 0x1e bytes C++
  mfc100ud.dll!CWnd::WindowProc(unsigned int message, unsigned int wParam, long lParam)  Line 2087 + 0x20 bytes C++
  mfc100ud.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam)  Line 257 + 0x1c bytes C++
  mfc100ud.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam)  Line 420 C++
  mfc100ud.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam)  Line 420 + 0x15 bytes C++
  user32.dll!_InternalCallWinProc@20()  + 0x23 bytes 
  user32.dll!_UserCallWinProcCheckWow@32()  + 0xb3 bytes 
  user32.dll!_SendMessageWorker@20()  + 0xee bytes 
  user32.dll!_SendMessageW@16()  + 0x49 bytes 
  user32.dll!_IsDialogMessageW@8()  + 0xef46 bytes 
> mfc100ud.dll!CWnd::IsDialogMessageW(tagMSG * lpMsg)  Line 198 C++
  mfc100ud.dll!CWnd::PreTranslateInput(tagMSG * lpMsg)  Line 4713 C++
  mfc100ud.dll!CDialog::PreTranslateMessage(tagMSG * pMsg)  Line 82 C++
  OrderXMLReaderShell.exe!CFindDlg::PreTranslateMessage(tagMSG * pMsg)  Line 56 C++
  mfc100ud.dll!CWnd::WalkPreTranslateTree(HWND__ * hWndStop, tagMSG * pMsg)  Line 3311 + 0x14 bytes C++
  mfc100ud.dll!AfxInternalPreTranslateMessage(tagMSG * pMsg)  Line 233 + 0x12 bytes C++
  mfc100ud.dll!CWinThread::PreTranslateMessage(tagMSG * pMsg)  Line 777 + 0x9 bytes C++
  mfc100ud.dll!AfxPreTranslateMessage(tagMSG * pMsg)  Line 252 + 0x11 bytes C++
  mfc100ud.dll!AfxInternalPumpMessage()  Line 178 + 0x18 bytes C++
  mfc100ud.dll!CWinThread::PumpMessage()  Line 900 C++
  mfc100ud.dll!CWinThread::Run()  Line 629 + 0xd bytes C++
  mfc100ud.dll!CWinApp::Run()  Line 832 C++
  mfc100ud.dll!AfxWinMain(HINSTANCE__ * hInstance, HINSTANCE__ * hPrevInstance, wchar_t * lpCmdLine, int nCmdShow)  Line 47 + 0xd bytes C++
  OrderXMLReaderShell.exe!wWinMain(HINSTANCE__ * hInstance, HINSTANCE__ * hPrevInstance, wchar_t * lpCmdLine, int nCmdShow)  Line 26 C++
  OrderXMLReaderShell.exe!__tmainCRTStartup()  Line 547 + 0x2c bytes C
  OrderXMLReaderShell.exe!wWinMainCRTStartup()  Line 371 C
  kernel32.dll!@BaseThreadInitThunk@12()  + 0x12 bytes 
  ntdll.dll!___RtlUserThreadStart@8()  + 0x27 bytes 
  ntdll.dll!__RtlUserThreadStart@8()  + 0x1b bytes 

The execution flow got into CDialog::OnCancel virtual method. Here is the default MFC's implementation:

void CDialog::OnCancel()
{
 EndDialog(IDCANCEL);
}

It simply ends the dialog, thus destroying the window.

Lets find out how do we get there. The control flow is the following:

  1. Escape key is down
  2. WM_KEYDOWN message is queued into message queue
  3. AfxInternalPumpMessage gets the message from the queue and invokes AfxPreTranslateMessage
  4. CWnd::IsDialogMessage is reached
  5. IsDialogMessage WinAPI function is called by CWnd::IsDialogMessage; this function is the core of dialog management - it does things like keyboard navigation.
  6. There is a user32.dll!_SendMessageW@16() call from IsDialogMessageW
  7. Which brings us to CWnd::OnCommand with wParam equals to IDCANCEL
  8. End finally to CDialog::OnCancel

IsDialogMessageW examines the message and invokes SendMessage(hwndDlg, WM_COMMAND, MAKELONG(IDCANCEL, BN_CLICKED), ...);.

Short summary - MFC calls IsDialogMessage API function, which in turns emulates IDCANCEL button click, which is being handled by MFC eventually destroying the dialog.

It is not obvious why IsDialogMessageW emulates IDOK and IDCANCEL button clicks. I believe this is done to make developer's life easier. Imagine you have no control over the message loop, can't do any message pre translation. You'll have to handle Enter and Escape keys for every control on the dialog. That's pain.

What can we do to solve the problem? You can't change OS behavior for sure, but can do the following:

  1. Override CDialog::OnOK/OnCancel and do nothing

    The following applies:

    • Dialog is not destroyed on Enter or Escape
    • Focused inline controls don't receive WM_KEYDOWN for VK_ENTER and VK_ESCAPE codes
    • OK/Cancel button clicks have no effect
  2. Override CDialog::PreTranslateMessage and don't call the base if pMsg->message == WM_KEYDOWN && (pMsg->wParam == VK_ESCAPE || pMsg->wParam == VK_RETURN)

    If CDialog::PreTranslateMessage returns TRUE the following applies:

    • Dialog is not destroyed on Enter or Escape
    • Focused inline controls don't receive WM_KEYDOWN for VK_RETURN and VK_ESCAPE codes, unless you do dispatch them before CDialog::PreTranslateMessage returns
    • OK/Cancel button clicks have desired effect

    If CDialog::PreTranslateMessage returns FALSE the following applies:

    • MFC calls parent's PreTranslateMessage (which brings us back if the parent is a CDialog instance)
  3. Override CWinThread::PreTranslateMessage, examine the message and don't call the base

    The following applies:

    • CWnd::WalkPreTranslateTree is not invoked, thus disabling message pre translation along with IsDialogMessage call (specific messages only, it's not as scary as it seems, but hits the performance and hard to implement properly)

      If CWinThread::PreTranslateMessage returns TRUE the following applies:

      • Message is not dispatched
      • Focused inline controls don't receive WM_KEYDOWN for VK_RETURN and VK_ESCAPE codes

      If CWinThread::PreTranslateMessage returns FALSE the following applies:

      • Message is dispatched
      • Focused inline controls receive WM_KEYDOWN for VK_RETURN and VK_ESCAPE codes
    • The behavior is application wide

The very best option would be to override CWnd::IsDialogMessage and return in case of VK_RETURN and VK_ESCAPE, but this is impossible since CWnd::IsDialogMessage is not virtual. CWnd::IsDialogMessage is an API function wrapper, the closest item to modify the behavior.

So which method is the best? Each does the trick, but... Option 3 has serious drawback. Option 1 and 2 are class specific. I vote for option 2. You could create some base CDialog class with the trick and use it for all your dialogs.

Funny site error

Misspelling

Portal 2 installer

Fucking Date and Time Picker Controls or how to close DateTimePicker programmatically

Только что закончил фикс милейшего дефекта. DateTimePicker вываливал окно календаря и при щелчках мышью по заголовку родительского окна или в другие области оно оставалось висеть пока не выбрана дата.

Происходило это потому, что элемент управления DateTimePicker был создан в потоке отличном от потока окна верхнего уровня, в котором он находится. Да, знаю, многозадачный UI - это зло, но имеем то, что имеем.

В результате исследования выяснилось, что начиная с Windows Vista этой проблемы больше нет - окно закрывается в любом случае (маленькая поправочка - при использовании 6-й версии библиотеки comctl32). На Windows XP проблема имеет место быть в не зависимости от версии comctl32.

Помимо внедрения механизма, который позволяет перехватывать по запросу асинхронные сообщения со всех UI потоков, возникла еще одна задачка - програмно закрыть окно календаря.

Сначала показалось, что задачка из простых - было найдено сообщение DTM_CLOSEMONTHCAL, которое выполняет нужную функцию. После попытки разобраться почему вариант не рабочий выяснилось, что Minimum supported client - Windows Vista. А нам для Windows XP. Блядь-блядь-блядь!!!

Хрен с ним, решение все равно есть. Достаточно лишь понять как работает DateTimePicker. А он закрывает month calendar при нажатии клавиши Escape, а также при некоторых манипуляциях мышью. Также следует учесть, что элемент управления не теряет фокус во время отображения окна month calendar, а само выпадающее окно никогда не активируется.

Первое, что пришло в голову, - эмулировать нажатие Escape когда month calendar нужно закрыть програмно - выполнить SendKeys.SendWait("{ESC}");. Вариант оказался не рабочий. Причина весьма коварна - вызов этого метода запускает вложенный цикл сообщений и крутит его до тех пор, пока внедренные сообщения о нажатии клавиш не будут обработаны. А еще DateTimePicker запускает свой цикл сообщений, когда показывает окно календаря:

  user32.dll!_NtUserGetMessage@16()  + 0xc bytes 
  comctl32.dll!_DPLBD_MonthCal@8()  + 0x244 bytes 
  comctl32.dll!_DPLButtonDown@12()  + 0x79 bytes 
  comctl32.dll!_DatePickWndProc@16()  + 0x56b bytes 
  user32.dll!_InternalCallWinProc@20()  + 0x28 bytes 
  user32.dll!_UserCallWinProcCheckWow@32()  + 0xb7 bytes 
  user32.dll!_CallWindowProcAorW@24()  + 0x51 bytes 
  user32.dll!_CallWindowProcW@20()  + 0x1b bytes 
  System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.DefWndProc(ref System.Windows.Forms.Message m) Line 810 + 0x31 bytes C#
  System.Windows.Forms.dll!System.Windows.Forms.Control.DefWndProc(ref System.Windows.Forms.Message m) Line 5729 + 0xa bytes C#
  System.Windows.Forms.dll!System.Windows.Forms.Control.WmMouseDown(ref System.Windows.Forms.Message m, System.Windows.Forms.MouseButtons button, int clicks) Line 12909 + 0xc bytes C#
  System.Windows.Forms.dll!System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message m) Line 13761 C#
  System.Windows.Forms.dll!System.Windows.Forms.DateTimePicker.WndProc(ref System.Windows.Forms.Message m) Line 1686 C#

В этом цикле содержится логика закрытия окна календаря. Одно из ее составляющих - ожидание сообщения WM_KEYDOWN с VK_ESC. Сообщение при этом глотается, до окна оно не доходит. Именно поэтому первая попытка провалилась. Выход - использовать SendKeys.Send("{ESC}");, неблокирующий вызов, который не запускает вложенный цикл обработки сообщений, просто вставляет в очередь необходимые сообщения, которые в последствии обрабатываются циклом сообщений внутри DPLBD_MonthCal. Мне он тоже не подошел т.к. активировалось другое окно и оно же получало нажатие Escape. В результате я просто делаю Win32.PostMessage(Handle, Win32.WM_KEYDOWN, Win32.VK_ESC, IntPtr.Zero); и все пучком. Код стероидов:

/// <summary>
/// Month calendar visibility.
/// </summary>
public bool IsMonthCalendarShown
{
    get
    {
        return (IsHandleCreated
                && Win32.SendMessage(Handle, Win32.DTM_GETMONTHCAL, IntPtr.Zero, IntPtr.Zero) != IntPtr.Zero);
    }
}

/// <summary>
/// Closes month calendar if visible.
/// </summary>
/// <remarks>
/// This is guaranteed to work on Windows Vista and above. Under Windows XP this method uses a hack.
/// </remarks>
public void CloseMonthCalendar()
{
    if (!IsMonthCalendarShown)
    {
        return;
    }

    if (Win32.HasVistaAPI)
    {
        Win32.SendMessage(Handle, Win32.DTM_CLOSEMONTHCAL, IntPtr.Zero, IntPtr.Zero);
    }
    else
    {
        // NOTE: SendKeys.Send[Wait] can't be used here!
        // comctl32 runs its own message loop and awaits for WM_KEYDOWN with VK_ESC. It doesn't dispatch that however,
        // rather closes the month calendar instead. SendKeys.SendWait calls Application.DoEvents() which
        // runs message loop and does dispatch WM_KEY**** messages. So the month calendar is not closed.
        // SendKeys.Send might send input to wrong window (one being activated by mouse).
        //
        // HACK: So the only option here is to post WM_KEYDOWN with VK_ESC.
        //
        Win32.PostMessage(Handle, Win32.WM_KEYDOWN, Win32.VK_ESC, IntPtr.Zero);
    }
}

SendKeys suck

Недавно пришлось поколупаться в исходном коде класса SendKeys. Его отвратительное качество меня просто поразило. Но самый больший ахуй случился когда я там наткнулся на следующий WTF:

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] 
private static void LoadSendMethodFromConfig()
{ 
   if (!sendMethod.HasValue) 
   {
       sendMethod = SendMethodTypes.Default; 

       try
       {
           // read SendKeys value from config file, not case sensitive 
           string value = System.Configuration.ConfigurationManager.AppSettings.Get("SendKeys");
 
           if (value.Equals("JournalHook", StringComparison.OrdinalIgnoreCase)) 
               sendMethod = SendMethodTypes.JournalHook;
           else if (value.Equals("SendInput", StringComparison.OrdinalIgnoreCase)) 
               sendMethod = SendMethodTypes.SendInput;
       }
       catch {} // ignore any exceptions to keep existing SendKeys behavior
   } 
}

Если в файле конфигурации приложения отсутствует настройка SendKeys - value.Equals вываливает NullReferenceException, который успешно тушится блоком catch {}. Это пиздец, господа. Класс писал студент в качестве тестового задания для Microsoft? Не удивительно, что во фреймворке столько говнокода, ведь студента видимо приняли.

Copyright 2007-2011 Chabster