tags:

views:

97

answers:

3

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?

+3  A: 

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

JamesB
I open the dialog from several places, and I don't want to check every place.
Svein Bringsli
Then use a method that you can call from several places. Do the checks in that method and if ok, only then open the form
Marjan Venema
+3  A: 

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
I accepted Bharat's answer, even though your answer was almost identical. Sorry. He beat you by two seconds :-)
Svein Bringsli
@Svein - Here, SO shows my answer beat his with 37 seconds. But anyway it is close enough not to make a fuss about it. :-)
Sertac Akyuz
As Einstein said: the perception of time depends on your speed.
Uwe Raabe
@Uwe, Oh!, that must be it. I'm staying put while I probably should be moving! :p
Sertac Akyuz
+2  A: 

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
Thanks, that worked.
Svein Bringsli