How to block running two instances of the same program?

后端 未结 8 1275
暗喜
暗喜 2020-12-01 05:23

I need to make sure that user can run only one instance of my program at a time.
Which means, that I have to check programatically, whether the same program is already r

8条回答
  •  天命终不由人
    2020-12-01 06:16

    I scan the process list looking for the name of my apps executable with matching command line parameters then exit if there is a match.

    My app can run more than once, but I don't want it running the same config file at the same time.

    Obviously, this is Windows specific, but the same concept is pretty easy on any *NIX system even without specific libraries simply by opening the shell command 'ps -ef' or a variation and looking for your app.

       '*************************************************************************
       '     Sub: CheckForProcess()
       '  Author: Ron Savage
       '    Date: 10/31/2007
       '
       ' This routine checks for a running process of this app with the same
       ' command line parameters.
       '*************************************************************************
       Private Function CheckForProcess(ByVal processText As String) As Boolean
          Dim isRunning As Boolean = False
          Dim search As New ManagementObjectSearcher("SELECT * FROM Win32_process")
          Dim info As ManagementObject
          Dim procName As String = ""
          Dim procId As String = ""
          Dim procCommandLine As String = ""
    
          For Each info In search.Get()
             If (IsNothing(info.Properties("Name").Value)) Then procName = "NULL" Else procName = Split(info.Properties("Name").Value.ToString, ".")(0)
             If (IsNothing(info.Properties("ProcessId").Value)) Then procId = "NULL" Else procId = info.Properties("ProcessId").Value.ToString
             If (IsNothing(info.Properties("CommandLine").Value)) Then procCommandLine = "NULL" Else procCommandLine = info.Properties("CommandLine").Value.ToString
    
             If (Not procId.Equals(Me.processId) And procName.Equals(processName) And procCommandLine.Contains(processText)) Then
                isRunning = True
             End If
          Next
    
          Return (isRunning)
       End Function
    

提交回复
热议问题