防止同一個程序多次運行。 [VB.NET]

'*****************方法一:防止程序多次打開*****************
'      函數名:      IsInstanceRunning 
'      功  能:      判斷工程是否已運行 
'      參  數:      無 
'      返回值:      True  已運行    False  未運行 
'*******************************************************
Public Function IsInstanceRunning() As Boolean
    Dim current As Process = System.Diagnostics.Process.GetCurrentProcess()
    Dim processes As Process() = System.Diagnostics.Process.GetProcessesByName(current.ProcessName)
    'Loop  through  the  running  processes  in  with  the  same  name    
    Dim p As Process
    For Each p In processes
        'Ignore  the  current  process    
        If p.Id <> current.Id Then
            'Make  sure  that  the  process  is  running  from  the  exe  file.    
            If System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", "/") = current.MainModule.FileName Then
                'Return  the  other  process  instance.    
                Return True
            End If
       End If
    Next
    'No  other  instance  was  found,  return  null.    
    Return False
End Function   'RunningInstance   

'*****************方法二:防止程序多次打開*****************
Imports System.Diagnostics
If UBound(Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName))  _
 > 0 Then Eixt Sub
'Process.GetCurrentProcess.ProcessName 獲取當前運行程序的名稱。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章