检测指定进程是否在运行

vb.net:

          Private Function IsRunning(ByVal projname As String) As Boolean
        Dim CurrentProcess As Process = Process.GetCurrentProcess()
        Dim processes As Process() = Process.GetProcessesByName("AAA")
        Dim p As Process
        For Each p In processes
            If p.Id <> CurrentProcess.Id Then
                If CurrentProcess.MainModule.FileName = Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", "\") Then
                    'MsgBox("系统已打开", MsgBoxStyle.Information, "提示")
                    'Me.Close()
                    Return True
                End If
            End If
        Next
        Return False
    End Function


c#:

      private Boolean IsRunning(string projname)
        {
            Process CurrentProcess = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(projname);
            //Process p;
            foreach(Process p in processes)
            {
                if (p.Id != CurrentProcess.Id )
                {
                    if (CurrentProcess.MainModule.FileName == System.Reflection.Assembly.GetExecutingAssembly().Location.Replace('/','\\'))
                    {
                        return true;
                    }
                }
            }


            return false;
        }

注:该方法需要放置在需要执行的程序中,先执行该函数,如果返回True则退出程序。

你可能感兴趣的:(vb.net)