Forms Delphi

Title: Using the Tag property to centralize and simplify form creation
Question: When you have too many dinamically created forms, sometimes you repeat a lot of code that is alike, for the create-show-free cycle of them. The following demonstrates how you can use the Tag property of your menu items to centralize the code for your dynamically created forms. It makes the code a lot cleaner.
Answer:
Paste the following unit as your mainform; the code supposes you have other 3 forms, with their default names. Also, the secondary forms must not be included in the autocration list of the project:
{--snip--}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,Forms,
Dialogs, StdCtrls, Menus;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
MnuMain: TMenuItem;
MnuShowForm2: TMenuItem;
MnuShowForm3: TMenuItem;
MnuShowForm4: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure CommonMenuItemsClickEvt(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
uses Unit2, Unit3, Unit4;
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
{Place a Pointer to the a form in each menu item's tag.
This is so to craete the forms dynamically, with no need for a
*case* statement:}
MnuShowForm2.Tag:= Integer(TForm2);
MnuShowForm3.Tag:= Integer(TForm3);
MnuShowForm4.Tag:= Integer(TForm4);
{Note that this is only possible because an object reference is a
pointer, and any
pointer is the same size in bytes as an integer.}
end;
//MenuItems' OnClick events must point to this handler:
procedure TForm1.CommonMenuItemsClickEvt(Sender: TObject);
var
f: TForm;
begin
if (Sender as TMenuItem).Tag 0 then
begin
f := TFormClass((Sender as TMenuItem).Tag).Create(nil);
try
f.ShowModal;
finally
f.Free;
end; //try
end //if
else //just to prevent any weirdness:
Application.MessageBox('Not implemented.', 'Oops...', MB_OK or
MB_ICONERROR);
end;
end.
{--snip--}