program onlyRunOne;
uses
Forms,Windows,SysUtils, Dialogs,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
var
myMutex:HWND;
begin
myMutex:=CreateMutex(nil,false,'11111'); //名称只能全系统唯一。
if WaitForSingleObject(myMutex,0)<>wait_TimeOut then
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end else begin
Application.MessageBox('已经有一个事例运行了,本事例不能运行','提示',mb_ok+mb_IconInformation);
Application.Terminate;
end;
end.
hMutex:=CreateMutex(nil,true,'test1');
if GetLastError=ERROR_ALREADY_EXISTS then
begin
Application.MessageBox('已经有一个事例运行了,本事例不能运行','提示',mb_ok+mb_IconInformation);
Application.Terminate;
Abort;
end;
//其中 test1 是随便 起的字符,但如果别的程序也用这个名字 ,那2个程序也只能找开一个哦。
网上找了很多方法,很多有漏洞
自己总结实验了出来 下面是正确的
用法:
如我们要判断'Live.exe'程序是否正在运行/是否已经启动
if exe_is_running(Live) then
....
else
....
uses
Forms,Windows,SysUtils,Dialogs,
Unit1 in 'Unit1.pas' {Form1},
Unit2 in 'Unit2.pas' {Form2},
Unit3 in 'Unit3.pas' {Form3};
{$R *.res}
var
myMutex:HWND;
begin
myMutex:=CreateMutex(nil,false,'hkOneCopy');
if WaitForSingleObject(myMutex,0)<>wait_TimeOut then
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.CreateForm(TForm2, Form2);
Application.CreateForm(TForm3, Form3);
Application.Run;
end
else
begin
showmessage('你已经运行了程序在屏幕右下角处');
end;
end.