Svein Bringsli
Svein Bringsli

Reputation: 5748

How do I close a modal form right after opening it?

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?

Upvotes: 12

Views: 21458

Answers (4)

Mauro
Mauro

Reputation: 1

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

Upvotes: 0

James
James

Reputation: 9985

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

Upvotes: 5

Bharat
Bharat

Reputation: 6866

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;

Upvotes: 16

Sertac Akyuz
Sertac Akyuz

Reputation: 54832

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;

Upvotes: 20

Related Questions