Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var
- Semafor : THandle;
- begin
- // Don't start twice ... if already running bring this instance to front
- Semafor := CreateSemaphore(nil, 0, 1, 'MY_APPLICATION_IS_RUNNING');
- if ((Semafor <> 0) and // application is already running
- (GetLastError = ERROR_ALREADY_EXISTS))
- then begin
- RestoreWindow('TMyApplication');
- CloseHandle(Semafor);
- Halt;
- end;
- Application.CreateForm(....);
- Application.Initialize;
- Application.Run;
- CloseHandle(Semafor);
- end;
- procedure RestoreWindow(aFormName : string);
- var
- Wnd,
- App : HWND;
- begin
- Wnd := FindWindow(PChar(aFormName), nil);
- if (Wnd <> 0)
- then begin // Set Window to foreground
- App := GetWindowLong(Wnd, GWL_HWNDPARENT);
- if IsIconic(App)
- then ShowWindow(App, SW_RESTORE);
- SetForegroundwindow(App);
- end;
- end;
- var
- mutex: THandle;
- mutexName: string;
- begin
- mutexName := ConstructMutexName();
- mutex := CreateMutex(nil, False, PChar(mutexName));
- if mutex = 0 then
- RaiseLastOSError; // Couldn't open handle at all.
- if GetLastError = Error_Already_Exists then begin
- // We are not the first instance.
- SendDataToPreviousInstance(...);
- exit;
- end;
- // We are the first instance.
- // Do NOT close the mutex handle here. It must
- // remain open for the duration of your program,
- // or else later instances won't be able to
- // detect this instance.
- Application.Initialize;
- Application.CreateForm(...);
- Application.Run;
- end.
- HANDLE Mutex;
- const char MutexName[] = "MyUniqueProgramName";
- Mutex = OpenMutex(MUTEX_ALL_ACCESS, false, MutexName);
- if (Mutex)
- throw Exception("Program is already running.");
- else
- Mutex = CreateMutex(NULL, true, MutexName);
- Program test
- var
- handle :HWND;
- begin
- handle := FindWindow('TMySuperApp', nil);
- if IsWindow(handle) then
- begin
- //app is running
- exit;
- end.
- Application.Initialize;
- Application.CreateForm(TMySuperApp, SuperApp);
- Application.Run;
- end;
Add Comment
Please, Sign In to add comment