Le fait d’avoir à détecter si un programme est déjà lancé est un problème récurant, donc comme on nombre de développeur je sors de temps en temps la snippet suivante
Vb
Public Shared Function IsNotFirstInstance() As Boolean Dim Apps As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcesses() Dim App As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() Try For i As Int32 = 0 To i < Apps.Length If Apps(i).Id <> App.Id _ AndAlso Apps(i).ProcessName = App.ProcessName Then Return True End If Next Return False Finally Apps = Nothing App = Nothing End Try End Function
C#
public static Boolean IsNotFirstInstance() { System.Diagnostics.Process[] Apps = System.Diagnostics.Process.GetProcesses(); System.Diagnostics.Process App = System.Diagnostics.Process.GetCurrentProcess(); try { for (Int32 i = 0; i < Apps.Length; i++) { if (Apps[i].Id != App.Id & Apps[i].ProcessName == App.ProcessName) return true; } return false; } finally { Apps = null; App = null; } }
Mais avec linq le choses changent, et comme toujours dans le bon sens ;)
Vb
Public Shared Function IsNotFirstInstance() As Boolean Dim current As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess() Try Return System.Diagnostics.Process.GetProcesses() _ .Any(Function(c) c.ProcessName = current.ProcessName _ AndAlso c.Id <> current.Id) Finally current = Nothing End Try End Function
C#
public static Boolean IsNotFirstInstance() { System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess(); try { return System.Diagnostics.Process.GetProcesses() .Any(c => c.ProcessName == current.ProcessName & c.Id != current.Id); } finally { current = null; } }
après c’est une histoire de gouts, mais je trouve cela tout de même plus lisible.