问题
I have a program with Form1 and Form2. How can I open form2 from form1 clicking a button?
回答1:
Just a little more info
having this in your Project.cpp: Application->CreateForm(__classid(TForm2), &Form2); means that the form will be created when you start your application.
if you want to create the form your self when clicking the button do the following
TForm2 *Form = new TForm2( this );
Form->ShowModal();
if for instance you need to use a custom constructor you can also create a new form passing in any values you need. for example
TForm2 *Form = new TForm2( this, "My New Form" , Now() );
Form->ShowModal();
The above method besides setting the owner of the form passes in a string and a TDateTime you could then uses them in your forms constructor to do some stuff.
remember if you create these forms your self you will need to delete them.
to allow other buttons or controls also access you form you need to do the following
in the private section of the header add the following
TForm2 *Form;
now back in the cpp you will need to create teh form before you can use it, this changes slightly from the earlier one
Form = new TForm2( this );
Form->ShowModal();
but now if you want to access the form to say update the caption you can simply do
Form->Caption = "Changed Caption";
the caption on the form will now be changed
回答2:
Borland what? Delphi? C++ Builder?
For Delphi:
Ensure that Delphi created an instance of Form2
in Project.dpr: Application.CreateForm(TForm2, Form2);
Then add the Form2
unit name to one of the uses
clauses in the Form1
unit, then you can use Form2.Show;
or Form2.ShowModal;
.
For C++:
Ensure that C++ Builder created an instance of Form2
in Project.cpp: Application->CreateForm(__classid(TForm2), &Form2);
Then add an #include
statement for the .hpp file of the Form2
unit to the .cpp file of the Form1
unit, then you can use Form2->Show();
or Form2->ShowModal();
.
来源:https://stackoverflow.com/questions/10794869/how-do-i-open-a-new-form-with-a-button-using-c-builder