转贴: 如何防止一个程序执行两次 这是一个比较简单的防止程序执行两次的方法implementationvar hnd: THandle;initializationhnd := CreateMutex(nil, True, 'irgendwaseinmaliges');if GetLastError = ERROR_ALREADY_EXISTS then Halt;finalizationif hnd <> 0 then CloseHandle(hnd);end.
var hMutex:HWND; Ret:Integer;hMutex:=CreateMutex(nil,False,'系统信息'); Ret:=GetLastError; If Ret=ERROR_ALREADY_EXISTS Then begin Application.MessageBox('注意!程序已在运行!','系统信息',MB_OK+MB_ICONWARNING); ReleaseMutex(hMutex); halt; end;
判断只运行一个程序(单实例)的方法一般有3种,前面已经列举了FindWindow方法和 CreateMutex方法,还有一种是全局原子法,具体如下: 在.dpr的文件如下: program Project1;uses Forms,windows,dialogs, Unit1 in 'Unit1.pas' {Form1};{$R *.RES} const iAtom='SingleAPP'; begin if GlobalFindAtom(iAtom)=0 then Begin GlobalAddAtom(iAtom); Application.initialize; Application.createForm(tForm1,form1); Application.run; GlobalDeleteAtom(globalFindAtom(iAtom)); End else showmessage('您已经运行了一个程序'); End.
把以下代码代码加到工程文件里(选择Project-->view source)var WinHandle:THANDLE; begin WinHandle:=FindWindow(nil,'某某系统'); if WinHandle=0 then Application.Initialize; Application.CreateForm(TForm1,Form1); Application.Run; else begin showmessage('程序已经运行!') //这句可去掉,直接切换到已运行的实例 windows.setfocus(WinHandle) windows.setforeground(WinHandle) end; end.
如何防止一个程序执行两次
这是一个比较简单的防止程序执行两次的方法implementationvar hnd: THandle;initializationhnd := CreateMutex(nil, True, 'irgendwaseinmaliges');if GetLastError = ERROR_ALREADY_EXISTS then Halt;finalizationif hnd <> 0 then CloseHandle(hnd);end.
hMutex:HWND;
Ret:Integer;hMutex:=CreateMutex(nil,False,'系统信息');
Ret:=GetLastError;
If Ret=ERROR_ALREADY_EXISTS Then
begin
Application.MessageBox('注意!程序已在运行!','系统信息',MB_OK+MB_ICONWARNING);
ReleaseMutex(hMutex);
halt;
end;
CreateMutex方法,还有一种是全局原子法,具体如下:
在.dpr的文件如下:
program Project1;uses
Forms,windows,dialogs,
Unit1 in 'Unit1.pas' {Form1};{$R *.RES}
const iAtom='SingleAPP';
begin
if GlobalFindAtom(iAtom)=0 then
Begin
GlobalAddAtom(iAtom);
Application.initialize;
Application.createForm(tForm1,form1);
Application.run;
GlobalDeleteAtom(globalFindAtom(iAtom));
End
else
showmessage('您已经运行了一个程序');
End.
WinHandle:THANDLE;
begin
WinHandle:=FindWindow(nil,'某某系统');
if WinHandle=0 then
Application.Initialize;
Application.CreateForm(TForm1,Form1);
Application.Run;
else
begin
showmessage('程序已经运行!') //这句可去掉,直接切换到已运行的实例
windows.setfocus(WinHandle)
windows.setforeground(WinHandle)
end;
end.