ThN
ThN

Reputation: 3276

Why form destroy event is called more than once?

I never noticed it in my program before, but for one of my TForm I have a destroy event, which frees an object, is called or fired more than once. I don't understand why.

procedure THTrendFrm.FormDestroy(Sender: TObject);
begin
  LogAlarm.Free;  <---Invalid Pointer Operation exception is raised
end;

Thanks in advance,

Update: Here is the FastMM message window right after my program is shutdown. TAlarmMsg is the class from which LogAlarm is created. enter image description here enter image description here

Upvotes: 0

Views: 1634

Answers (3)

ThN
ThN

Reputation: 3276

Thanks to David Heffernan and others. I found my problem and fixed it. The TForm in question was being created twice in my project file like so.

Application.CreateForm(HTrendFrm, HTrend);

That explains why destroy was called twice.

Once I removed the duplicate line, it is shutting down fine.

Upvotes: 1

Wouter van Nifterick
Wouter van Nifterick

Reputation: 24086

It depends on how you've created LogAlarm.

If LogAlarm is a TComponent descendant, and you've created it with the form as an owner, you shouldn't call Free on it, because the component will automatically be cleaned up once the form gets destroyed.

Or if you insist on cleaning it up yourself, leave owner as nil during creation.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596352

The TForm.OnDestroy event is not called multiple times, so you have to be freeing the LogAlarm object somewhere else in your code before the OnDestroy event is triggered.

Upvotes: 2

Related Questions