Author Topic: Escape Key Closing MessageDlg When Called From the KeyDown Event Handler  (Read 780 times)


  • New Member
  • *
  • Posts: 43
When catching the escape key in FormKeyDown and then immediately asking a question in a MessageDlg, the MessageDlg shows up very quickly and then disappears.  In the example below, I see the MessageDlg flash briefly and then see the ShowMessage with "Yes pressed".  It looks like the escape is also closing down the MessageDlg.  When catching a different key in the example below (i.e. not escape) all works as expected.

Code: Pascal  [Select][+][-]
  1. procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState
  2.   );
  3. begin
  4.   if Key = VK_ESCAPE
  5.   then if MessageDlg('Choose Yes or No.',mtConfirmation,[mbYes,mbNo],0) = mrYes
  6.        then ShowMessage('Yes pressed')
  7.        else ShowMessage('No pressed');
  9.   inherited;
  10. end;

This was working correctly in Lazarus 1.8.4.

Lazarus v2.1.0 r61720
fpc v3.3.1 r42727
Widgetset = cocoa
CPU family = x86_64

Thank you.


  • Hero Member
  • *****
  • Posts: 2918
  • Compiler Developer
The problem is that the dialog reacts to the UP event for the Escape key. You show the dialog before the UP event is received and thus the dialog will receive that right away and close itself. So it should work if you put your code into a handler for OnKeyUp.


  • Hero Member
  • *****
  • Posts: 4180
  • My goal: build my own game engine using Lazarus
I cannot reproduce the behavior on Lazarus 2.0.2 Linux GTK2. I think it is OS dependent behavior.


  • Hero Member
  • *****
  • Posts: 8322
I cannot reproduce the issue either (Window 10).

If I could I would have checked the following modifications:
  • Erase the Key (Key := 0) before showing the message box
  • Use the KeyPress event instead of KeyDown. Key handling seems to me to be more "complete" here than in KeyDown.
Mainly Lazarus trunk / fpc 3.2.0 / all 32-bit on Win-10, but many more...


  • New Member
  • *
  • Posts: 43
I have tried to "erase the key (Key := 0)" prior to the MessageDlg, but it did no good.

I'll try KeyPress / KeyUp to see if I can get the desired behavior.  However, please note that on previous versions with Carbon on Mac the functionality was as expected using KeyDown.

Thank you.


  • Hero Member
  • *****
  • Posts: 10754
The issue is simply that the OnKeyDown keeps firing (which it should!).
The solution is simply to connect to OnKeyUp!!!!

I have explained that many times before....And fires only once, which is what you want.

Alternatively - if it is the only use - set OnKeyDown to nil in the event itself. Then it also fires just once.)bad practice, but possible)
« Last Edit: August 19, 2019, 08:07:55 pm by Thaddy »


TinyPortal © 2005-2018