本文提供一些关于程序互斥的思路。注:此文章为本站(Lob.cn)乐博网原创,可以自由转载和传播,但希望能保留本站的作者和信息来源,谢谢!如果大家对此问题或者关于“VB.Net操作注册表”的话题感兴趣,就一起来SmallBasic.cn 快乐编程讨论把他做得更完善吧!
VB.Net互斥 简单代码:
本文中举例程序名均为"乐博网.exe"
Imports System.Diagnostics
If UBound(Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)) > 0 Then Me.Dispose()
不难看出,以上方法只能检测当前进程列表中是否已经存在"乐博网.exe"这个进程,如果存在则自动阻止再次运行;而如果应用程序名从"乐博网.exe"改为"lob.cn.exe"或者其他文件名,则检测无效。乐博网提供思路和实现需要的相关代码。检测该进程对应的程序的md5数值,来判断唯一性,检测时加入阻止与当前进程中具有相同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 '更多vb.net源代码和实例,请关注乐博网lob.cn
Return sb.ToString().ToLower
End Function
乐博网附:获取当前启动程序的绝对路径
path_lob = Application.ExecutablePath
乐博网附:获取进程中程序的绝对路径
Imports System.Management ' lob.cn提示 System.Management要“添加引用”
Dim CommandLine Dim Searcher As New ManagementObjectSearcher("Root\CIMV2", "Select * From Win32_Process where Name ='乐博网.exe'") For Each QueryObj As ManagementObject In Searcher.Get()
CommandLine = QueryObj("CommandLine")
MsgBox("乐博网.exe的绝对路径为" & CommandLine)
Next
==========================结束
|