Mutexes, as core objects of the system, can span processes (critical areas are not), and we can use mutexes to prevent programs from repeatedly booting.
Work idea:
Try to open a Mutex object with a custom name first with OpenMutex, and no such object exists until the failure description is opened;
If you do not have this object, immediately use CreateMutex to establish a, this time the program should be the first time to start;
When you start again, the OpenMutex will have a result, and then force the exit.
Finally, the Mutex object is freed with CloseHandle at the end of the program.
function OpenMutex(
dwDesiredAccess: DWORD; {打开权限}
bInheritHandle: BOOL; {能否被当前程序创建的进程继承}
pName: PWideChar {Mutex 对象的名称}
): THandle; stdcall; {成功返回 Mutex 的句柄; 失败返回 0}
Note that the CreateMutex function here should have a name, because the OpenMutex to use;
In addition, the second argument of CreateMutex is no longer important (that is, True and False) because it is judged by its name.
Programs can write like this: unit Unit1
Interface
uses
Windows, Messages, sysutils, variants, Classes, Graphics, contro LS, 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 = ' M Ymutex ';
Procedure Tform1.formcreate (sender:tobject);
Begin
If OpenMutex (mutex_all_access, False, Namemutex) <> 0 then
begin
ShowMessage (' This program started '); application.terminate;
End;
Hmutex: = CreateMutex (Nil, False, Namemutex);
End;
Procedure Tform1.formdestroy (sender:tobject);
Begin
CloseHandle (Hmutex);
End;
End.
This is generally written in the DPR main program, so that the later-launched program executes some useless code:program Project1;
uses
Forms, Windows,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
var
hMutex: THandle;
const
NameMutex = 'MyMutex';
begin
{主线程入口}
if OpenMutex(MUTEX_ALL_ACCESS, False, NameMutex) <> 0 then
begin
MessageBox(0, '该程序已启动', '提示', MB_OK);
Application.Terminate;
end;
hMutex := CreateMutex(nil, False, NameMutex);
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TForm1, Form1);
Application.Run;
CloseHandle(hMutex);
{主线程出口}
end.