Jump to content

_SingletonPID() - Enforce only one instance of the program running. Use AutoIt's hidden window.


guinness
 Share

Recommended Posts

OK; thanks for your input.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 2 weeks later...

It's flawed, because what happens if I copy the executable (that's already running) and rename it? It runs twice. So hmm yeah, probably not a great post.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

It's flawed, because what happens if I copy the executable (that's already running) and rename it? It runs twice. So hmm yeah, probably not a great post.

If you rename it, then you're running "another" program, so you probably want to be running another copy of it... ;)  (it's a question of logic).

But you are right. It's just I prefer things simpler (I use the same name for both the au3 and exe).

Link to comment
Share on other sites

If you rename it's still the same code.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

$s = StringReplace(@ScriptName,".au3",".exe")
$p = ProcessList($s) ; --- Check if this program is already running. If so then exit.
If $p[0][0] > 1 Or $s <> "MyProgram.exe" Then Exit

This works for me. I'll insist I'm not a programmer, I simply do a couple scripts once in a while. Because of it, I try to use the simplest way that works FOR ME.

Well... if then you have a 3rd program that you rename to mine and then you run mine... sure, it will think it's already running.

BTW guiness, I never said mine was a great post. I simply said it was simpler (in other words).

Link to comment
Share on other sites

Please stop this now. Simple != better. You will learn this valuable lesson one day.

For others who are programmers, hard coding the application name in the program is such a bad design flaw, that will more than likely lead to additional problems.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Please stop this now. Simple != better. You will learn this valuable lesson one day.

For others who are programmers, hard coding the application name in the program is such a bad design flaw, that will more than likely lead to additional problems.

You're the one saying that making it "pro" style is better. I never said my way was better nor worse, just simpler FOR ME (incase you didn't read it).

You should also know that there's never a "best design", specially in programming. Take a look at all the modern crap we have in nowadays software. I'm sure you know a lot of good examples.

And to stop this now, as you put it, I don't think it's a good way to stick in everyone's face something like "the ways the pros do it is the right way", specially when AutoIt was made for simplicity. If we wanted to be pros I'm sure we'd all be learning some more advanced language...

You'll have to excuse me though. I'm not a developer. I'm a guy that knows a tiny bit of many things but unfortunently isn't pro at any. I do what I can.

Link to comment
Share on other sites

  • 5 months later...

I just copied your example script and tested and got this error:

warning: $STR_REGEXPARRAYGLOBALMATCH: possibly used before declaration.
                    '\|SINGLETON_PID:(\d+)\R', $STR_REGEXPARRAYGLOBALMATCH)

 

When I try

ConsoleWrite($STR_REGEXPARRAYGLOBALMATCH & @CRLF)

Then the error really occurs.

I didn't forget to #include <StringConstants.au3> .

 

I use Autoit 3.3.10.2

 

What $STR_REGEXPARRAYGLOBALMATCH should be ?

Thanks :)

 

EDIT:

I guess it's supposed to be 3 according to this source:

https://www.autoitscript.com/autoit3/docs/functions/StringRegExp.htm

Edited by Guest
Link to comment
Share on other sites

Yeah that constant is in v3.3.12.0 and above. Glad you worked it out.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Yeah that constant is in v3.3.12.0 and above. Glad you worked it out.

Yes it works.
But not as I expected .. Please read what I wrote in the code

#include <StringConstants.au3>
#include <MsgBoxConstants.au3>


If _SingletonPID('appname_main_1', 1) Then _
Exit MsgBox(64,'Error','The script is already running')

; ##########################################################

; In this area there is another global code that may or may not execute the
; command 'Exit'

; ** This area may call to different GUIs functions that I want them to be under 'appname_main_1'

; ..............
; ..............

; let assume that the code didn't execute Exit (didn't exit and the script continues to run and
; perform the next instructions.

; ##########################################################


; ** Now I want to change 'appname_main_1' to 'appname_main_2' because every GUI that will be here
; Should be under 'appname_main_2'

; So I do this:
If _SingletonPID('appname_main_2', 1) Then _
Exit MsgBox(64,'Error','The script is already do X'&@CRLF& _
'Please close X (what the script doing) and try again')
; ^^^^ but this does not working


; If you run the script twice:
; 1) in mode appname_main_1
; 2) in mode appname_main_2

; then what I expect is that the script will not block itself because there is nothing wrong here
; because each mod run once.
; But it not working..




; #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 (see below). Default is 0.
;                       0 - Exit the script with the exit code -1 if another instance already exists.
;                       1 - Return the PID of the initial executable.
; Return values .: Success - 0 (no additional instances exist).
;                  Failure - The PID of the initial instance.
; Author ........: guinness with initial ideas by Valik for _Singleton() & KaFu for _EnforceSingleInstance().
; Example .......: Yes
; ===============================================================================================================================
Func _SingletonPID($sOccurenceName, $iFlag = 0)
    Local $iReturn = 0
    Local $hAutoItWnd = WinGetHandle($sOccurenceName)
    If @error Then
        AutoItWinSetTitle($sOccurenceName & @AutoItPID)
        $hAutoItWnd = WinGetHandle($sOccurenceName & @AutoItPID)
        AutoItWinSetTitle($sOccurenceName)

        Local Const $hControl = ControlGetHandle($hAutoItWnd, '', 'Edit1')
        ControlSetText($hAutoItWnd, '', $hControl, ControlGetText($hAutoItWnd, '', $hControl) & @CRLF & _
                '|SINGLETON_PID:' & @AutoItPID & @CRLF)
    Else
        If $iFlag = Default Then $iFlag = 0
        If BitAND($iFlag, 1) Then ; $SINGLETON_PID
            $iReturn = Int(StringRegExp(ControlGetText($hAutoItWnd, '', ControlGetHandle($hAutoItWnd, '', 'Edit1')) & @CRLF & _
                    '|SINGLETON_PID:0' & @CRLF, _
                    '\|SINGLETON_PID:(\d+)\R', 3)[0])
        Else
            Exit -1
        EndIf
    EndIf
    Return $iReturn
EndFunc   ;==>_SingletonPID

 

Thanks :)

 

Edited by Guest
Fixed code
Link to comment
Share on other sites

Your code is wrong. What is $iSingleton for starters?

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I did not understand your question about iSingleton.

But I know what I want to achieve and how ..

By definition this UDF should not work this way?

what wrong in the code? the way I use your UDF or the design?

EDIT:

Oops .. I know now what is wrong ..
I was sure I do not need to run it .. good lesson: Always run the code before posting

Edited by Guest
Link to comment
Share on other sites

OK.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I guess I know what you think ..
This code is not meant to show the problem in reality(show the problem actually occurs in the computer) . That was not my intention when I wrote the code ..
The goal is to show the problem through comments ...
I'm just tired to write anything that presents the problem in reality.

 

But OK I will edit the post and write  better code that actually make the problem to happen in the computer..

 

EDIT:

The new code:

#include <StringConstants.au3>
#include <MsgBoxConstants.au3>


If Not @Compiled Then Exit MsgBox(16,'','You must to compile the script!')

If _SingletonPID('appname_main_1', 1) Then _
Exit MsgBox(64,'Error','The script is already running')

; ##########################################################

; In this area there is another global code that may or may not execute the
; command 'Exit'

; ** This area may call to different GUIs functions that I want them to be under 'appname_main_1'
GUI1()
Func GUI1()
    If MsgBox($MB_YESNO,'Some GUI','Some GUI under appname_main_1'&@CRLF& _
    'Click Yes to Exit the script or No to continume.') = 6 Then Exit
EndFunc

; ..............
; ..............

; let assume that the code didn't execute Exit (didn't exit and the script continues to run and
; perform the next instructions.

; ##########################################################


; ** Now I want to change 'appname_main_1' to 'appname_main_2' because every GUI that will be here
; Should be under 'appname_main_2'

; So I do this:
If _SingletonPID('appname_main_2', 1) Then _
Exit MsgBox(64,'Error','The script is already do X'&@CRLF& _
'Please close X (what the script doing) and try again')
; ^^^^ but this does not working

GUI2()
Func GUI2()
    MsgBox(0,'Some GUI','Some GUI under appname_main_2')
EndFunc

; If you run the script twice:
; 1) in mode appname_main_1
; 2) in mode appname_main_2

; then what I expect is that the script will not block itself because there is nothing wrong here
; because each mod run once.
; But it not working..




; #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 (see below). Default is 0.
;                       0 - Exit the script with the exit code -1 if another instance already exists.
;                       1 - Return the PID of the initial executable.
; Return values .: Success - 0 (no additional instances exist).
;                  Failure - The PID of the initial instance.
; Author ........: guinness with initial ideas by Valik for _Singleton() & KaFu for _EnforceSingleInstance().
; Example .......: Yes
; ===============================================================================================================================
Func _SingletonPID($sOccurenceName, $iFlag = 0)
    Local $iReturn = 0
    Local $hAutoItWnd = WinGetHandle($sOccurenceName)
    If @error Then
        AutoItWinSetTitle($sOccurenceName & @AutoItPID)
        $hAutoItWnd = WinGetHandle($sOccurenceName & @AutoItPID)
        AutoItWinSetTitle($sOccurenceName)

        Local Const $hControl = ControlGetHandle($hAutoItWnd, '', 'Edit1')
        ControlSetText($hAutoItWnd, '', $hControl, ControlGetText($hAutoItWnd, '', $hControl) & @CRLF & _
                '|SINGLETON_PID:' & @AutoItPID & @CRLF)
    Else
        If $iFlag = Default Then $iFlag = 0
        If BitAND($iFlag, 1) Then ; $SINGLETON_PID
            $iReturn = Int(StringRegExp(ControlGetText($hAutoItWnd, '', ControlGetHandle($hAutoItWnd, '', 'Edit1')) & @CRLF & _
                    '|SINGLETON_PID:0' & @CRLF, _
                    '\|SINGLETON_PID:(\d+)\R', 3)[0])
        Else
            Exit -1
        EndIf
    EndIf
    Return $iReturn
EndFunc   ;==>_SingletonPID

BUT this bug does not occur in this case!
so or the bug is in my head or something in my source code caused the bug to happen.

I guess it's the second option.

I'll check it out, debug when I will have time and come here with what I found if there is really a bug..

In any case, the code I posted here maybe useful as good example

Edited by Guest
Link to comment
Share on other sites

  • 9 months later...

Hi,

is there a clean method to launch a new instance (from shortcut) but tell it to restore and "show" the existing instance before it exits
Or if it would be preferable to exit the existing one and continue with the new one which should show the GUI by default
(For me both ways should suit the purpose)

 can you please give an example on how its done

TIA
 

Link to comment
Share on other sites

I posted an example here a few months ago.

EDIT

 

 

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Link to comment
Share on other sites

  • 2 months later...


I know the idea of this function is to do these :
1. while an instance ID already exists and running , exit any newly started Occurrences
2. check what instance of the Occurrence is now running

I'm looking how to run  this with two IDs :
with the first ID I'm interested to somehow to register the instance ID as running and allow other instances of the same ID to start (identifier_2 in code example)
but with the next new ID (when started) while the first ID instance exists,I want it to see the first instance ID and exit
with the second I just want it to runs as _SingletonPID($iSngl, 0)  (as prescribed)

I know I need to modify the _SingletonPID function (any ideas how I can accomplish this ?)

this is what I started with : using 'identifier_1' and 'identifier_2'

StringRegExp($CmdLine[1], "r$", 1)
If @error == 0 Then
    _Single('identifier_2')
Else
    _Single('identifier_1')
EndIf
Func _Single($iSngl)
    If @Compiled Then
        If $iSngl = 'identifier_1' Then
            Local $iSingleton = _SingletonPID('identifier_2', 1) ;if an Occurence ID of 'identifier_2'  exists then exit else run as 'identifier_1' with not allowing new instances of 'identifier_1' 
            If $iSingleton Then
                Exit
            Else
                _SingletonPID($iSngl, 0) ;run ID without allowing new instances of this ID
            EndIf
        EndIf
        If $iSngl = 'identifier_2' Then
            Local $iSingleton = _SingletonPID($iSngl, 1) ;accept and recognize running extra instances of 'identifier_2'
            If $iSingleton Then
                Local $iSingleton = _SingletonPID($iSngl, 1)
            EndIf
        EndIf
    EndIf
EndFunc   ;==>_Single

TIA

Edited by Deye
Link to comment
Share on other sites

  • 5 months later...

This function is great. My use: If another instance of the program is opened, activate it with WinActivate.

Since _SingletonPID() returns the PID and not the handle of the window, we will need another function called _GetHwndFromPID(), which can be found in the Help File. I've included it in the example below:

 

#include <StringConstants.au3>

; Search for another instance of this script
Local $singleton = _SingletonPID('YourScript',1)

; If another instance was found
if $singleton <> 0 Then

    ; Get a handle on that instance
    $handle = _GetHwndFromPID($singleton)
    
    ; Activate that window
    WinActivate($handle)
    
    ; Exit this script
    Exit
EndIf


Func _SingletonPID($sOccurenceName, $iFlag = 0)
    Local $iReturn = 0
    Local $hAutoItWnd = WinGetHandle($sOccurenceName)
    If @error Then
        AutoItWinSetTitle($sOccurenceName & @AutoItPID)
        $hAutoItWnd = WinGetHandle($sOccurenceName & @AutoItPID)
        AutoItWinSetTitle($sOccurenceName)

        Local Const $hControl = ControlGetHandle($hAutoItWnd, '', 'Edit1')
        ControlSetText($hAutoItWnd, '', $hControl, ControlGetText($hAutoItWnd, '', $hControl) & @CRLF & _
                '|SINGLETON_PID:' & @AutoItPID & @CRLF)
    Else
        If $iFlag = Default Then $iFlag = 0
        If BitAND($iFlag, 1) Then ; $SINGLETON_PID
            $iReturn = Int(StringRegExp(ControlGetText($hAutoItWnd, '', ControlGetHandle($hAutoItWnd, '', 'Edit1')) & @CRLF & _
                    '|SINGLETON_PID:0' & @CRLF, _
                    '\|SINGLETON_PID:(\d+)\R', $STR_REGEXPARRAYGLOBALMATCH)[0])
        Else
            Exit -1
        EndIf
    EndIf
    Return $iReturn
EndFunc   ;==>_SingletonPID


Func _GetHwndFromPID($PID)
    $hWnd = 0
    $winlist = WinList()
    Do
        For $i = 1 To $winlist[0][0]
            If $winlist[$i][0] <> "" Then
                $iPID2 = WinGetProcess($winlist[$i][1])
                If $iPID2 = $PID Then
                    $hWnd = $winlist[$i][1]
                    ExitLoop
                EndIf
            EndIf
        Next
    Until $hWnd <> 0
    Return $hWnd
EndFunc;==>_GetHwndFromPID

 

Edited by mexykanu
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...