先在mainform中声明Hmutex: THandle;
然后在*.dpr 文件中:
Hmutex := CreateMutex(nil, false, '程序名');
if not (waitForSingleObject(hmutex, 0) <> wait_timeout) then
begin
Application.MessageBox('此程序已经运行,不能再次打开!', '警告!', MB_ICONERROR);
halt;
end
else
;;;;;
//Create a Semaphore in memory - If this is the first instance, then
//it should be 0.
hSem := CreateSemaphore(nil, 0, 1, semNm);
//Now, check to see if the semaphore exists
if ((hSem <> 0) AND (GetLastError() = ERROR_ALREADY_EXISTS)) then
begin
CloseHandle(hSem);
//We'll first get the currently executing window's handle then change its title
//so we can look for the other instance
hWndMe := FindWindow(nil, wTtl);
SetWindowText(hWndMe, 'zzzzzzz');
//What we want to do now is search for the other instance of this window
//then bring it to the top of the Z-order stack.
hWndMe := FindWindow(nil, wTtl);
if (hWndMe <> 0) then
begin
if IsIconic(hWndMe) then
ShowWindow(hWndMe, SW_SHOWNORMAL)
else
SetForegroundWindow(hWndMe);
end;
Result := True;
//Could put the Halt here, instead of in the FormCreate method,
//unless you want to do some extra processing.
//Halt;
end;
end;
end.
//在主窗口创建时加入
Self.caption:='数据服务管理';
if DoIExist(Self.Caption) then Halt;