Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

delphi - Access a control inherited by the child form in parent form

I use Delphi XE3. I have two form, TParentForm and TChildForm. TParentForm contains Button1, and TChildForm is inherited from it.

Then when I operate Button1 in TParentForm, in the following procedure TParentFrm.Button2Click(Sender: TObject), is it operating on the instance of Button1 in ChildForm when I invoke ChildForm.Show and click Button1?

type
  TParentFrm = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TChildForm = class(TParentFrm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  ParentFrm: TParentFrm;

implementation

{$R *.dfm}

procedure TParentFrm.Button2Click(Sender: TObject);
begin
  Button1.Caption := '&Test';  // Is it operating on Childform's button1 when I
                               // create and show child form and then click 
                               //"Button2".
end;

Test unit:

procedure TForm1.Button1Click(Sender: TObject);
begin
      ChildForm.Show;
end;



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Short answer: Your code will change caption of the Button1 control that is on same form instance that the Button2 that you clicked on.


Long answer: When you use code Button1.Caption := '&Test'; you basically instructs compute to go and find component named Button1 and change its Caption property to &Test. When computer performs this search it always does this within the instance of the form from which the code was called for.

So if your code is called from OnClick event that was fired by button that is placed on your ParentForm it will affect the Button1 that is on your ParentForm.

If the code is called from OnClick event that was fired from a button on your ChildForm it will affect the Bu8tton1 that is on your child form.

Yes at this point your application have two buttons named Button1. One is on your ParentForm and another is on your ChildForm

In fact you can also create another instance of your ParentForm and clicking on Button2 on that form will affect the Button1 on that instance of the form and not the original instance of your ParentForm.

I hope my explanation is understandable enough. If not do let me know.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...