2007. április 7., szombat

How to put forms into a DLL


Problem/Question/Abstract:

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:

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

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

if Assigned(ShowMyModuleForm) then
  ShowMyModuleForm := nil;
if MyDLLHandle <> 0 then
  FreeLibrary(MyDLLHandle);
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;
var
  a: TForm2;
begin
  Application := App;
  Screen := Scr;
  a := TForm2.Create(Application.MainForm);
  {"Application.MainForm" could also be "nil" or any valid value}
  a.ShowModal;
  a.Free;
end;

exports
  ShowMyForm;

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:

var
  OldApp: TApplication;
  OldScr: TScreen;

initialization
  OldApp := Application;
  OldScr := Screen;
finalization
  Screen := OldScr;
  Application := OldApp;
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.

Nincsenek megjegyzések:

Megjegyzés küldése