B4J Code Snippet Singleton and Process Functions

Hi

In this thread I wrote some functions to make sure only one instance of the application is running. Here are the functions, both of them depend on jShell :

  • ProcessExists just checks if a process exists.. nothing fancy.
B4X:
Sub ProcessExists(ExeName As String) As Boolean
    Dim Result As ShellSyncResult
    Dim sh As Shell
    sh.InitializeDoNotHandleQuotes("", "tasklist", Array As String("/FI", $""IMAGENAME eq ${ExeName}""$))
    Result = sh.RunSynchronous(2000)
    Return Not(Result.StdOut.Contains("No tasks are running"))
End Sub

  • ProcessCount checks how many processes with the same name (regex pattern) are running. You can use this function to make sure only one process of you app is running, as in the example below:
B4X:
Sub AppStart (Form1 As Form, Args() As String)
    If ProcessCount("myApp\.exe") > 1 Then
        Log("Only one instance of myApp allowed.")
        ExitApplication(2)
    End If
End Sub

Sub ProcessCount(ExeNamePattern As String) As Int
    Dim Count As Int = 0
    Dim Result As ShellSyncResult
    Dim sh As Shell
    sh.InitializeDoNotHandleQuotes("", "tasklist", Null)
    Result = sh.RunSynchronous(2000)
    If Result.Success = False Then Return Count
    Dim Match As Matcher  = Regex.Matcher2(ExeNamePattern, Regex.CASE_INSENSITIVE, Result.StdOut)
    Do While Match.Find
        Count = Count + 1
    Loop
    Return Count
End Sub
 
Last edited:
Top