Author: Peter Thörnqvist
Adding a form to a DLL is actually quite simple. Depending on the type of form
(modal or mode-less) you have to proceed differently. This article explains how it
is done.
Answer:
To add a form to a DLL you have to remember these things:
assign the calling programs Application.Handle to the DLL's Application.Handle
write one or two exported functions that handles the interaction with the calling
program
include sharemem as the first unit in the DLL's uses clause if the exported
functions uses strings
if you are going to show a mode-less form, you should return a handle to your form
in the "Show" function and require it as a parameter in the "Close" function
always create the form with the Application object as the Owner
restore the DLL's Application.Handle after closing the form
You don't have to do anything special to add a form to a DLL: just add the forms
filename to the uses clause and Delphi will compile it right into the DLL.
Here's an example with both modal and mode-less invocation. The examples just
return an integer value, but you could of course return just about anything:
1 library testDLL;
2 3 uses4 myTestFrom, SysUtils, Controls;
5 6 var7 OldApphandle: longint = 0;
8 9 { these functions are used with the mode-less form: }10 11 { AppHandle is the *calling* applications Handle }12 13 function ShowTestForm(AppHandle: integer): longint;
14 var15 F: TmyTestForm;
16 begin17 { save current handle unless it's already done }18 if Application.Handle <> AppHandle then19 OldAppHandle := Application.Handle;
20 { assign new }21 Application.Handle := AppHandle;
22 { create and show form }23 F := TmyTestForm.Create(Application);
24 F.Show;
25 Result := longint(F);
26 end;
27 28 { the input value, Handle, must be the same value as returned by ShowTestForm }29 30 function CloseTestForm(Handle: longint): integer;
31 var32 F: TmyTestForm;
33 begin34 { typecast back to TForm (some sanity checks here would not be bad...}35 F := TmyTestForm(Handle);
36 Result := F.SomeIntValue;
37 F.Close;
38 F.Free;
39 { restore previous handle }40 Application.Handle := OldAppHandle;
41 end;
42 43 { this function is used to show the form modally }44 45 function ShowTestFormModal(AppHandle: integer): longint;
46 var47 F: TmyTestForm;
48 begin49 OldAppHandle := Application.Handle;
50 try51 Application.Handle := AppHandle;
52 F := TmyTestForm.Create(Application);
53 try54 if F.ShowModal = mrOK then55 Result := F.SomeIntValue
56 else57 Result := -1;
58 finally59 F.Free;
60 end;
61 finally62 Application.Handle := OldAppHandle;
63 end;
64 end;
65 66 { finally export the functions: }67 68 exports ShowTestForm name 'ShowTestForm', CloseTestForm name 'CloseTestForm',
69 ShowTestFormModal name 'ShowTestFormModal';
70 71 begin72 end.