12

From my application I wish to open a dialog, which should close immediately (after a short message) under some circumstances.

I've tried this:

procedure TForm2.FormActivate(Sender: TObject);
begin
  if SomeCondition then
  begin
    ShowMessage('You can''t use this dialog right now.');
    close;
    modalresult := mrCancel;
  end;
end;

but the dialog remains open. I've also tried to put the code in the OnShow event, but the result is the same.

Why doesn't this work?

Svein Bringsli
  • 5,640
  • 7
  • 41
  • 73

4 Answers4

20

Post a WM_CLOSE message instead of calling close directly;

ShowMessage('You can''t use this dialog right now.');
PostMessage(Handle, WM_CLOSE, 0, 0);
modalresult := mrCancel;
Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
16

try this one

procedure TForm2.FormActivate(Sender: TObject);
begin
  ShowMessage('You can''t use this dialog right now.');
  PostMessage(Self.Handle,wm_close,0,0);
end;
Bharat
  • 6,828
  • 5
  • 35
  • 56
5

Wouldn't it be easier to check the certain circumstance before the form opens, and not open it?

I can't see a reason for the form to stay open, it should disappear immediatly after clicking OK on the show message dialog.

The showmessage is blocking so you won't be able to close until that's OK'd (if you need to close before then you could return a different modal result (or make your own up which doesn't clash with the existing ones like mrUnavailable = 12). Then you could show the message if the ModalResult was mrunavailable.

If it is running the code and just not closing then try using Release instead of close.

Edit: if you re-using the same form in several places don't use Release unless you want to recreate the form every time! Post the close message as the others have suggested

James
  • 9,774
  • 5
  • 34
  • 58
0

You can try a timer:

  • set the timer a low interval (20)
  • on the OnTimer event, close the form;
  • enable the timer on the FormActivate event
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Mauro
  • 1