5

作成したコンポーネントに、メイン フォームのパネルを渡します。

以下は、非常に単純化された例です。

procedure TMy_Socket.StatusPanel_Add(AStatusPanel: TPanel);

このコンポーネントは、必要に応じてパネルのキャプションを更新します。

私のメイン プログラムでFreeAndNilは、次にコンポーネントがパネルを更新しようとすると、AV が発生します。理由はわかりました。コンポーネントのパネルへの参照が未定義の場所を指しています。

パネルが解放されて参照できないことがわかっている場合、コンポーネント内でどのように検出できますか?

試してみif (AStatusPanel = nil)ましたが、そうではありませんnil。まだアドレスがあります。

4

2 に答える 2

7

Panel のFreeNotification()メソッドを呼び出してから、TMy_Socketコンポーネントで仮想Notification()メソッドをオーバーライドする必要がありTPanelます。

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; 

TPanel代わりに、一度に1 つだけを追跡する場合:

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; 
于 2012-09-19T19:10:38.743 に答える
3

別のコンポーネントが解放されたときにコンポーネントに通知する必要がある場合は、 を参照してくださいTComponent.FreeNotification。それはまさにあなたが必要とするものでなければなりません。

于 2012-09-19T17:22:13.863 に答える