1) When a process attaches the DLL
2) When a thread attaches the DLL
3) When a process detaches the DLL
4) When a thread detaches the DLL
Each DLL has an enty point. This entry point is implemented as a callback function. It is called by system when a set of event occurs. Function has default name DllMain. A DLL that doesn't want to be loaded by a certain caller can simply return False in its DllMain() function once it detects who's calling.
In Delphi, DLLProc is used to specify a procedure that is invoked every time a DLL's entry point is called. A procedure assigned to DLLProc takes one Integer parameter (Reason).
The GetModuleFileName() API function returns the name of the caller module if you pass 0 as its first argument. Such a parameter is the handle of the module whose name you want to know.
When the Reason parameter is DLL_PROCESS_ATTACH, setting ExitCode to a nonzero value causes the entry point to return false.
Here's a sample code, we are allowing only MyCallingApp.exe to load the library (note: the DLL in this example has NO code except the DLLMain procedure):
procedure DllMain(reason: integer) ;
buf : array[0..MAX_PATH] of char;
loader : string;
case reason of
GetModuleFileName(0, buf, SizeOf(buf)) ;
loader := buf;
if Pos('MyCallingApp.exe', loader) > 0 then
ExitCode := -1
DllProc := @DllMain;
//more DLL code here...
Delphi tips navigator:
» Grayscaling a bitmap
« How to get the current line and column from a Memo