在VB.net 下如何判断已经有一个程序的实例在运行》??

解决方案 »

  1.   

    If (UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0) Then '防止程序被重复运行
    MsgBox("程序正在运行, 请检查窗口是否被最小化。", 48, "系统工具箱")
    End If
      

  2.   

    在程序开始的时候,调用下面这个函数,看返回是不是为空.  这个可以避免程序同名的问题(使用process.ID)  
     
    Public  Shared  Function  RunningInstance()  As  Process    
       
             Dim  current  As  Process  =  Process.GetCurrentProcess()    
       
             Dim  processes  As  Process()  =  Process.GetProcessesByName(current.ProcessName)    
       
     
       
             'Loop  through  the  running  processes  in  with  the  same  name    
       
             Dim  process  As  Process    
       
             For  Each  process  In  processes    
       
                       'Ignore  the  current  process    
       
                       If  process.Id  <>  current.Id  Then    
       
                                 'Make  sure  that  the  process  is  running  from  the  exe  file.    
       
                                 If  [Assembly].GetExecutingAssembly().Location.Replace("/",  "\")  =  current.MainModule.FileName  Then    
       
                                           'Return  the  other  process  instance.    
       
                                           Return  process    
       
                                 End  If    
       
                       End  If    
       
             Next  process    
       
             'No  other  instance  was  found,  return  null.    
       
             Return  Nothing    
       
    End  Function  'RunningInstance
      

  3.   

    防止程序多运运行(通过调试)
     Private Function IsInstanceRunning() As Boolean
            Dim current As Process = System.Diagnostics.Process.GetCurrentProcess()
            Dim processes As Process() = System.Diagnostics.Process.GetProcessesByName(current.ProcessName)
            Dim p As Process
            For Each p In processes
                If p.Id <> current.Id Then
                    If System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", "\") = current.MainModule.FileName Then
                        Return True
                        End
                    End If
                End If
            Next
            Return False
        End Function
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim a As Boolean
            a = IsInstanceRunning()
            If a = True Then
                MsgBox("程序已经运行", , "系统")
            Else
            End If
        End Sub