Function:
; #FUNCTION# ==================================================================================================================== ; Name ..........: _SingletonPID ; Description ...: Enforce a design paradigm where only one instance of the script may be running. ; Syntax ........: _SingletonPID($sOccurenceName[, $iFlag = 0]) ; Parameters ....: $sOccurenceName - String to identify the occurrence of the script. ; $iFlag - [optional] Optional parameters. Default is 0. ; 0 - Exit the script with the exit code -1 if another instance already exists. ; 1 - Return the PID of the main executable and without exiting the script too. ; Return values .: Success - 0 No other process is running. ; Failure - The PID of the main executable. ; Author ........: guinness with initial ideas by Valik for _Singleton & KaFu for _EnforceSingleInstance. ; Example .......: Yes ; =============================================================================================================================== Func _SingletonPID($sOccurenceName, $iFlag = 0) Local $hWnd = WinGetHandle($sOccurenceName) If @error Then AutoItWinSetTitle($sOccurenceName) $hWnd = WinGetHandle($sOccurenceName) ControlSetText($hWnd, '', ControlGetHandle($hWnd, '', 'Edit1'), @AutoItPID) Else If BitAND($iFlag, 1) Then Return Number(ControlGetText($hWnd, '', ControlGetHandle($hWnd, '', 'Edit1'))) Else Exit -1 EndIf EndIf Return 0 EndFunc ;==>_SingletonPID
Example 1:
Example 2:
Local $iSingleton = _SingletonPID('myUniqueName', 1) If $iSingleton = 0 Then MsgBox(4096, '', 'This is the first instance of the program running: ' & $iSingleton) Else MsgBox(4096, '', 'There is another instance running. This PID is: ' & $iSingleton) ; Wait for the process to close. ProcessWaitClose($iSingleton, 5) ; Reset _SingletonPID to current process since the previous one was closed. $iSingleton = _SingletonPID('myUniqueName', 1) MsgBox(4096, '', 'This is now the first instance of the program running: ' & $iSingleton) EndIf
Edited by guinness, 18 October 2012 - 01:32 PM.




