【转】VB.Net互斥实现单程序运行的方法。
vb2010吧
全部回复
仅看楼主
level 9
lipeiyi2006 楼主
[大笑]
2012年01月25日 04点01分 1
level 9
lipeiyi2006 楼主
本文提供一些关于程序互斥的思路。
假设当前程序名为1.exe
VB.Net互斥 简单代码:
Imports System.Diagnostics
If UBound(Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)) > 0 Then Me.Dispose()
不难看出,以上方法只能检测当前进程列表中是否已经存在1.exe进程,如果存在则自动阻止再次运行;而如果应用程序名从"1.exe"改为"2.exe"或者其他文件名,则检测无效。
我们可以检测该进程对应的程序的md5数值,来判断唯一性,检测时加入阻止与当前进程中具有相同md5数值的程序加载,这样就更完美了。
Public Function MD5CalcFile(ByVal filepath As String) As String
  Using reader As New System.IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read)
   Using md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
    Dim hash() As Byte = md5.ComputeHash(reader)
    Return ByteArrayToString(hash)
   End Using
  End Using
End Function
Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
 Dim sb As New System.Text.StringBuilder(arrInput.Length * 2)
 For i As Integer = 0 To arrInput.Length - 1
  sb.Append(arrInput(i).ToString("X2"))
 Next
 Return sb.ToString().ToLower
End Function
path_lob = Application.ExecutablePath’获取进程中程序的绝对路径
Imports System.Management ' System.Management 要“添加引用”
  Dim CommandLine
  Dim Searcher As New ManagementObjectSearcher("Root\CIMV2", "Select * From Win32_Process where Name ='1.exe'")
  For Each QueryObj As ManagementObject In Searcher.Get()
   CommandLine = QueryObj("CommandLine")
   MsgBox("1.exe的绝对路径为" & CommandLine)
  Next

2012年01月25日 04点01分 2
level 13
如果把第二次运行的那个EXE用UPX之类的打个包,MD5就不一样了。你的那个就没用了……
2012年02月26日 00点02分 4
level 9
lipeiyi2006 楼主
Message Digest Algorithm MD5 为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护。
http://baike.baidu.com/view/7636.htm
2012年04月02日 05点04分 7
level 2
其实我觉得可以把所有进程的映射路径的MD5值都算一遍,在和当前进程路径做比较,就怕太费时,而且提前把算好的MD5值保存到my名空间防止沙盒等压缩运行。
2017年10月08日 13点10分 8
level 9
不用这么麻烦,my命名空间是加密的,可以把程序集固定一个名字然后存放在setting空间,运行是只要非current进程有重名或current进程名不等于保存名就结束当前进程便可保证单开。但是缺点是其他重名应用会影响本应用运行,因此需要取个特别的名字。至于被篡改可以考虑每个对象的gethashcode,必定计算极快,所有类都默认继承object,都会有这个方法。以上都是vb独有的优势,建议发挥专长。
2017年10月16日 23点10分 9
1