熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Delphi編程 >> 正文

自定義事件實現不同窗體間的通訊Delphi篇

2022-06-13   來源: Delphi編程 
要實現子窗體與父窗體之間的通訊有多種方法(比如重載子窗體的構造函數將父窗體的引用作為參數傳遞給子窗體)下面我要介紹的是利用自定義事件的方法它能夠最大程度的避免模塊之間的耦合充分體現面向對象的優點
  先將效果圖展示給大家
  
[[The No Picture]]

  下面是實現代碼
  
  Unit //子窗體
  
  type
  //聲明自定義事件的類型(類似於C#中的委托)
  TMyEventHandle = procedure (Sender: TObject; Content: string) of object;
  
  TForm = class(TForm)
  ComboBox: TComboBox;
  Label: TLabel;
  procedure ComboBoxClick(Sender: TObject);
  private
  FOnSelectionChanged: TMyEventHandle;
  public
  //聲明自定義事件
  property OnSelectionChanged: TMyEventHandle
  read FOnSelectionChanged write FOnSelectionChanged;
  end;
  
  procedure TFormComboBoxClick(Sender: TObject);
  begin
  //當選擇改變時觸發自定義的事件
  if Assigned(FOnSelectionChanged) then
  FOnSelectionChanged(Self ComboBoxText);
  end;
  
  Unit //父窗體
  
  type
  TForm = class(TForm)
  btnOpenForm: TButton;
  Edit: TEdit;
  Label: TLabel;
  procedure btnOpenFormClick(Sender: TObject);
  private
  m_frm: TForm;
  
  procedure frm_SelectionChanged(Sender: TObject; Content: string);
  public
  constructor Create(AOwner: TComponent); override;
  destructor Destroy; override;
  end;
  
  constructor TFormCreate(AOwner: TComponent);
  begin
  inherited Create(AOwner);
  
  m_frm := TFormCreate(Self);
  
  //指定當m_frm的自定義事件發生時的處理程序
  m_frmOnSelectionChanged := frm_SelectionChanged;
  end;
  
  destructor TFormDestroy;
  begin
  m_frmFree;
  
  inherited Destroy;
  end;
  
  procedure TFormfrm_SelectionChanged(Sender: TObject; Content: string);
  begin
  EditText := Content;
  end;
  
  procedure TFormbtnOpenFormClick(Sender: TObject);
  begin
  m_frmShowModal;
  end;
From:http://tw.wingwit.com/Article/program/Delphi/201311/24690.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.