Mutex, as the core object of the system, can be cross-process (the critical section won't work). We can use mutex object to prohibit Program Start again.
Working ideas:
First use openmutex to open a mutex object with a custom name. If it fails to be opened, this object does not exist before;
If you do not have this object before, use createmutex to create one immediately. At this time, the program should be started for the first time;
When you start the service again, the openmutex will have the result, and then force exit.
At the end of the program, use closehandle to release the mutex object.
Function openmutex (dwdesiredaccess: DWORD; {open permission} binherithandle: bool; {whether it can be inherited by the process created by the current program} pname: pwidechar {mutex object name}): thandle; stdcall; {The mutex handle is returned successfully; 0 is returned if the mutex handle fails}
Note that the createmutex function here should have a name, because openmutex is required;
In addition, the second parameter of createmutex is no longer important (both true and false), because it is determined by its name.
The program can write as follows:
Unit unit1; interfaceuses windows, messages, sysutils, variants, classes, graphics, controls, forms, dialogs; Type tform1 = Class (tform) Procedure formcreate (Sender: tobject ); procedure formdestroy (Sender: tobject); end; var form1: tform1; implementation {$ R *. DFM} var hmutex: thandle; const namemutex = 'mymutex '; Procedure tform1.formcreate (Sender: tobject); begin if openmutex (mutex_all_access, false, namemutex) 0 then begin showmessage ('started this program '); application. terminate; end; hmutex: = createmutex (nil, false, namemutex); end; Procedure tform1.formdestroy (Sender: tobject); begin closehandle (hmutex); end.
This is generally written in the DPR main program, saving some useless execution of the later started program.Code:
program project1; uses forms, windows, unit1 in 'unit1. PAS '{form1}; {$ R *. res} var hmutex: thandle; const namemutex = 'mymutex '; begin {main thread entry} If openmutex (mutex_all_access, false, namemutex) 0 then begin MessageBox (0, 'This program has been started ', 'hprompt', mb_ OK); application. terminate; end; hmutex: = createmutex (nil, false, namemutex); application. initialize; application. mainformontaskbar: = true; application. createform (tform1, form1); application. run; closehandle (hmutex); {main thread exit} end.