How can I detect that a component has been freed?

I have a component that I create and then pass it a panel in my main form.

Here is a very simplified example:

procedure TMy_Socket.StatusPanel_Add(AStatusPanel: TPanel); 

This component will then update the panel title as needed.

In my main program, if I have a FreeAndNil panel, the next time the component tries to update the panel, I get AV. I understand why: the component link to the panel now indicates the location is undefined.

How can I detect inside a component if the panel has been freed, so I know that I can not refer to it?

I tried if (AStatusPanel = nil) , but it is not nil , it still has an address.

+4
source share
2 answers

You must call the Panel FreeNotification() method and then add the TMy_Socket component to override the virtual Notification() method, for example (given your naming scheme, I assume that you can add several TPanel controls to your component):

 type TMy_Socket = class(TWhatever) ... protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; ... public procedure StatusPanel_Add(AStatusPanel: TPanel); procedure StatusPanel_Remove(AStatusPanel: TPanel); ... end; procedure TMy_Socket.StatusPanel_Add(AStatusPanel: TPanel); begin // store AStatusPanel as needed... AStatusPanel.FreeNotification(Self); end; procedure TMy_Socket.StatusPanel_Remove(AStatusPanel: TPanel); begin // remove AStatusPanel as needed... AStatusPanel.RemoveFreeNotification(Self); end; procedure TMy_Socket.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent is TPanel) and (Operation = opRemove) then begin // remove TPanel(AComponent) as needed... end; end; 

If you are tracking only one TPanel at a time:

 type TMy_Socket = class(TWhatever) ... protected FStatusPanel: TPanel; procedure Notification(AComponent: TComponent; Operation: TOperation); override; ... public procedure StatusPanel_Add(AStatusPanel: TPanel); ... end; procedure TMy_Socket.StatusPanel_Add(AStatusPanel: TPanel); begin if (AStatusPanel <> nil) and (FStatusPanel <> AStatusPanel) then begin if FStatusPanel <> nil then FStatusPanel.RemoveFreeNotification(Self); FStatusPanel := AStatusPanel; FStatusPanel.FreeNotification(Self); end; end; procedure TMy_Socket.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent = FStatusPanel) and (Operation = opRemove) then FStatusPanel := nil; end; 
+6
source

If your component should be notified of the release of another component, review TComponent.FreeNotification . This should be exactly what you need.

+3
source

Source: https://habr.com/ru/post/1435111/


All Articles