Reproduced in NetEase blog: http://jiafeng26.blog.163.com/blog/static/1754251920100140134147/
Windows is a multi-user and multi-task operating system that supports multipleProgramRun at the same time. If your program does not want users to run more than one simultaneously,
What should we do? This article describes how to avoid running multiple programs at the same time.
The createmutex function is an uncommon function in windows,
This function object can only have one instance in the system and is a mutex. Therefore, we can use this feature to easily implement our requirements.
[Original function declaration ]:
Function createmutex (lpmutexattributes: psecurityattributes; binitialowner: bool; lpname: pchar): thandle;
Function createmutex (lpmutexattributes: psecurityattributes; binitialowner: bool; lpname: pchar): thandle; <br/>
[Parameter description ]:
Lpmutexattributes is a pointer to the security_attributes structure type and can be set to null.
Whether the binitialowner initializes the mutex.
The name of the lpname mutex object.
The function returns a mutex handle.
When the program runs, an object is created. If the object already exists, it indicates that the program has been run ..
[The implementation process is as follows ]:
Create a new project. The form is form1.
Add a button named button1.
Double-click button to addCode
Procedure tform1.button1click (Sender: tobject );
VaR
HW: hwnd;
GT: integer;
Begin
Application. initialize;
Application. Title: = 'runmyfile ';
HW: = createmutex (nil, false, 'runmyfile'); {create a mutex object}
GT: = getlasterror;
If GT <> error_already_exists then {if no mutex object is found}
Begin
Application. createform (tform1, form1); {create form}
Application. Run;
End
Else
Begin
Application. MessageBox ('program already run', 'hs', mb_ OK );
Application. Terminate;
Releasemutex (HW); {release mutex}
End;
End;