How can I tell if another instance of my program is already running?
Answer
You can create a Semaphore stop the second execution and bring you running application to the screen. The aFormName is the name of your main form class in your application. Copy the code bellow into your *.dpr file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
var aHandle : THandle; //Semaphore begin // Don't start twice ... if already running bring this instance to front aHandle:= CreateSemaphore(nil, 0, 1, 'MY_APPLICATION_IS_RUNNING'); if ((aHandle<> 0) and // application is already running (GetLastError = ERROR_ALREADY_EXISTS)) then begin RestoreWindow('TMyApplication'); CloseHandle(aHandle); Halt; end; Application.CreateForm(....); Application.Initialize; Application.Run; CloseHandle(aHandle); 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; |