How to put forms into a DLL (Views: 101)


How to put forms into a DLL


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:

MyDLLHandle := LoadLibrary('Project2.DLL');
if MyDLLHandle <> 0 then
  @ShowMyModuleForm := GetProcAddress(MyDLLHandle, 'ShowMyForm')
  ShowMyModuleForm := nil;

Add a "Form1.OnDestroy" event and add this code to it:

if Assigned(ShowMyModuleForm) then
  ShowMyModuleForm := nil;
if MyDLLHandle <> 0 then
MyDLLHandle := 0;

Now drop a "TButton" onto the form and add an "OnClick" event with this code:

if (MyDLLHandle <> 0) and (Assigned(ShowMyModuleForm)) then
  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:

{$R *.res}

procedure ShowMyForm(App: TApplication; Scr: TScreen); stdcall;
  a: TForm2;
  Application := App;
  Screen := Scr;
  a := TForm2.Create(Application.MainForm);
  {"Application.MainForm" could also be "nil" or any valid value}



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:

  OldApp: TApplication;
  OldScr: TScreen;

  OldApp := Application;
  OldScr := Screen;
  Screen := OldScr;
  Application := OldApp;

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.

<< Back to main page