level 9
本文提供一些关于程序互斥的思路。
假设当前程序名为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分