function TFrmBackup.CheckInstance: Boolean;
var
h: HWnd;
RetValue: Cardinal;
hProcess, ProcessId: THandle;
begin
Result := True;
mutex := 0;
//Mutex erzeugen
mutex := Windows.CreateMutex(
nil, True, PChar(sMutex));
if (GetLastError = ERROR_ALREADY_EXISTS)
then
begin
Result := False;
h := 0;
//Handle der anderen Instanz suchen
repeat
h := FindWindowEx(0, h, '
TApplication', PChar(Application.Title))
until (h <> Application.Handle);
if (h <> 0)
then
begin
//prüfen, ob die Instanz hängt
if (SendMessageTimeOut(h, WM_NULL, 0, 0, SMTO_NORMAL
or SMTO_ABORTIFHUNG,
5000, RetValue) = 0)
then
begin
//ProzessId des hängenden Prozesses holen
GetWindowThreadProcessId(h, ProcessId);
if (ProcessId = 0)
then
Exit;
//hängenden Prozess beenden
hProcess := OpenProcess(PROCESS_TERMINATE, False, ProcessId);
if (hProcess <> 0)
then
try
TerminateProcess(hProcess, 255);
finally
CloseHandle(hProcess);
end;
end;
end;
end;
end;