A: If the form is already instantiated, then you can find it through the TScreen object.
for i := 0 to screen.FormCount - 1 do
if screen.forms[i].ClassName = 'TForm12' then
ShowMessage('Yo!');
If you want to give each form a name, and you are using the 16 bit version, then the easiest way to name the form would be to place this code on the form's OnCreate method:
name := copy(ClassName, 2, length(ClassName) - 1);
What this does is to remove the first character from the form's class name (traditionally a "T") turning TForm1 into Form1. Simple, yet elegant.
Now then, I had a call from a customer that had about 100 forms that he needed to create and run by number. This is more problematic as you can't look through the TScreen's list for it. Here is a solution to this problem...
This part is to be placed on the main form's unit. Its purpose
is to have a couple of arrays that can be referenced by number.
const
MaxNumberOfForms = 3; // ...to make the number of forms
used easily changable.
var
Form1: TForm1;
FormArray : array [1..MaxNumberOfForms] of TForm;
FormRefArray : array [1..MaxNumberOfForms] of TFormClass;
implementation
uses Unit3; // All of the units must be used here, of course.
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
FormArray[3] := FormRefArray[3].create(self);
FormArray[3].ShowModal; // ...or whatever you need to
do.
FormArray[3].free;
end;
Now then, each other form must set itself up in the main form's array
of TFormClass. This is how that part is carried out:
unit Unit3; // This unit goes with Form3.
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs;
type
TForm3 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
uses unit1; // This unit must be able to use the main form's unit.
{$R *.DFM}
procedure TForm3.FormCreate(Sender: TObject);
begin
FormArray[3] := Self;
end;
initialization
FormRefArray[3] := TForm3 // Hard code the number here.
end.
The last part about hard coding the number means that you must
tell the array which class is to be associated with which array element.
Another way that this can be done is by using an extra unit which
has all of the form's information assigned from that point.
The advantage to this is that the code is centralized and easier to maintain,
but the idea behind its implementation remains the same.