表示: Delphi
C++
表示設定
フォームへの追加の引数の受け渡し
提供:RAD Studio
アプリケーション ユーザー インターフェイスの開発:インデックス への移動
一般に,アプリケーションで使用されるフォームは IDE で作成します。IDE で作成されると,フォームは作成されたフォームのオーナーを示す 1 つの引数 Owner をとるコンストラクタを持ちます。このオーナーは,呼び出し側のアプリケーションオブジェクトまたはフォームオブジェクトです。Owner は,nil にすることもできます。
フォームに追加の引数を渡すには別のコンストラクタを作成し,そのフォームを new 演算子を使ってインスタンス化します。たとえば,次のフォームクラスは,追加の引数 whichButton を持つ新しいコンストラクタを示しています。この新しいコンストラクタは,ユーザーが手作業でフォームクラスに追加します。
TResultsForm = class(TForm) ResultsLabel: TLabel; OKButton: TButton; procedure OKButtonClick(Sender: TObject); private public constructor CreateWithButton(whichButton: Integer; Owner: TComponent); end;
class TResultsForm : public TForm { __published: // IDE 管理のコンポーネント TLabel *ResultsLabel; TButton *OKButton; void __fastcall OKButtonClick(TObject *Sender); private: // ユーザー宣言 public: // ユーザー宣言 virtual __fastcall TResultsForm(TComponent* Owner); virtual __fastcall TResultsForm(int whichButton, TComponent* Owner); };
次に示すのは,追加の引数である whichButton が渡されるコンストラクタのコードです。このコンストラクタは whichButton 引数を使用して,フォーム上の Label コントロールの Caption プロパティを設定します。
constructor CreateWithButton(whichButton: Integer; Owner: TComponent); begin inherited Create(Owner); case whichButton of 1: ResultsLabel.Caption := "You picked the first button."; 2: ResultsLabel.Caption := "You picked the second button."; 3: ResultsLabel.Caption := "You picked the third button."; end; end;
void__fastcall TResultsForm::TResultsForm(int whichButton, TComponent* Owner) : TForm(Owner) { switch (whichButton) { case 1: ResultsLabel->Caption = "You picked the first button!"; break; case 2: ResultsLabel->Caption = "You picked the second button!"; break; case 3: ResultsLabel->Caption = "You picked the third button!"; } }
複数のコンストラクタを持つフォームのインスタンスを作成する場合は,目的に最適なコンストラクタを選択することができます。たとえば次に示すフォーム上のボタン用の OnClick ハンドラでは,2 つめのパラメータを使って TResultsForm のインスタンスを作成しています。
procedure TMainForm.SecondButtonClick(Sender: TObject); var rf: TResultsForm; begin rf := TResultsForm.CreateWithButton(2, self); rf.ShowModal; rf.Free; end;
void __fastcall TMainMForm::SecondButtonClick(TObject *Sender) { TResultsForm *rf = new TResultsForm(2, this); rf->ShowModal(); delete rf; }