Author: Jonas Bilinkevicius
How to put forms into a DLL
Answer:
Create a new Project. In between the word "type" and the "TForm1 = class..." put:
TMyProc = procedure(App: TApplication; Scr: TScreen); stdcall;
In the "private" area of "TForm1" add:
MyDLLHandle: THandle;
ShowMyModuleForm: TMyProc;
Add a "Form1.OnCreate" event and add this code to it:
1 MyDLLHandle := LoadLibrary('Project2.DLL');
2 if MyDLLHandle <> 0 then3 @ShowMyModuleForm := GetProcAddress(MyDLLHandle, 'ShowMyForm')
4 else5 ShowMyModuleForm := nil;
6 7 Add a "Form1.OnDestroy" event and add this code to it:
8 9 if Assigned(ShowMyModuleForm) then10 ShowMyModuleForm := nil;
11 if MyDLLHandle <> 0 then12 FreeLibrary(MyDLLHandle);
13 MyDLLHandle := 0;
14 15 Now drop a "TButton" onto the form and add an "OnClick" event with this code:
16 17 if (MyDLLHandle <> 0) and (Assigned(ShowMyModuleForm)) then18 ShowMyModuleForm(Application, Screen);
That's all for the EXE side. Now in the "Project Manager" right click the
"ProjectGroup1" (Top Node) and select "Add new project" from the popup menu. The
add "New Items" dialog comes up and under the "New" tab double click "DLL". In the
Project2.DLL source under the "uses" clause insert:
19 {$R *.res}20 21 procedure ShowMyForm(App: TApplication; Scr: TScreen); stdcall;
22 var23 a: TForm2;
24 begin25 Application := App;
26 Screen := Scr;
27 a := TForm2.Create(Application.MainForm);
28 {"Application.MainForm" could also be "nil" or any valid value}29 a.ShowModal;
30 a.Free;
31 end;
32 33 exports34 ShowMyForm;
35 36 end.
Add to the "uses" clause "Forms". Now in the "Project Manager" right click on the
"Project2.dll" and add a form and the class name should be named "TForm2". In the
"Implementation" area of the form put:
37 var38 OldApp: TApplication;
39 OldScr: TScreen;
40 41 initialization42 OldApp := Application;
43 OldScr := Screen;
44 finalization45 Screen := OldScr;
46 Application := OldApp;
47 end.
Put a "TButton" on the new form and set the "ModalResult" to "mrOk". Compile the
"dll" and the "exe". There's a sample form in DLL.
If you already have a form made that you want in the DLL just use it instead of "TForm2". Make sure the "initialization" and "finalization" code is in one, and only one, of the forms you put into the DLL. Without that code you may get unexpected results.