code_junkie

How do i tell if one instance of my program is running

Nov 13th, 2011
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. var
  2. Semafor : THandle;
  3.  
  4. begin
  5. // Don't start twice ... if already running bring this instance to front
  6. Semafor := CreateSemaphore(nil, 0, 1, 'MY_APPLICATION_IS_RUNNING');
  7. if ((Semafor <> 0) and // application is already running
  8. (GetLastError = ERROR_ALREADY_EXISTS))
  9. then begin
  10. RestoreWindow('TMyApplication');
  11. CloseHandle(Semafor);
  12. Halt;
  13. end;
  14.  
  15. Application.CreateForm(....);
  16. Application.Initialize;
  17.  
  18. Application.Run;
  19. CloseHandle(Semafor);
  20. end;
  21.  
  22. procedure RestoreWindow(aFormName : string);
  23. var
  24. Wnd,
  25. App : HWND;
  26.  
  27. begin
  28. Wnd := FindWindow(PChar(aFormName), nil);
  29. if (Wnd <> 0)
  30. then begin // Set Window to foreground
  31. App := GetWindowLong(Wnd, GWL_HWNDPARENT);
  32. if IsIconic(App)
  33. then ShowWindow(App, SW_RESTORE);
  34.  
  35. SetForegroundwindow(App);
  36. end;
  37. end;
  38.  
  39. var
  40. mutex: THandle;
  41. mutexName: string;
  42. begin
  43. mutexName := ConstructMutexName();
  44. mutex := CreateMutex(nil, False, PChar(mutexName));
  45. if mutex = 0 then
  46. RaiseLastOSError; // Couldn't open handle at all.
  47.  
  48. if GetLastError = Error_Already_Exists then begin
  49. // We are not the first instance.
  50. SendDataToPreviousInstance(...);
  51. exit;
  52. end;
  53. // We are the first instance.
  54.  
  55. // Do NOT close the mutex handle here. It must
  56. // remain open for the duration of your program,
  57. // or else later instances won't be able to
  58. // detect this instance.
  59.  
  60. Application.Initialize;
  61. Application.CreateForm(...);
  62. Application.Run;
  63. end.
  64.  
  65. HANDLE Mutex;
  66. const char MutexName[] = "MyUniqueProgramName";
  67. Mutex = OpenMutex(MUTEX_ALL_ACCESS, false, MutexName);
  68. if (Mutex)
  69. throw Exception("Program is already running.");
  70. else
  71. Mutex = CreateMutex(NULL, true, MutexName);
  72.  
  73. Program test
  74. var
  75. handle :HWND;
  76. begin
  77. handle := FindWindow('TMySuperApp', nil);
  78.  
  79. if IsWindow(handle) then
  80. begin
  81. //app is running
  82. exit;
  83. end.
  84.  
  85. Application.Initialize;
  86. Application.CreateForm(TMySuperApp, SuperApp);
  87. Application.Run;
  88. end;
Add Comment
Please, Sign In to add comment