Many times you'll want to make sure that your app is only running in once instance on any given machine. So how do you ensure this? Let's walk through it:
In a nutshell, all you need to do to enumerate all of the running processes is call the GetProcesses shared method of the Process class. When using just one dimension, I prefer to use an ArrayList vs an Array (which is what GetProcesses returns) so I used AddRange to get the data into my ArrayList:
| VB.NET Dim al As New ArrayList a.AddRange(Process.GetProcesses()) comboBox1.DataSource = al |
| C# ArrayList al = new ArrayList(); al.AddRange(Process.GetProcces()); comboBox1.DataSource = al; |
| VB.NET Private Function ShouldRunApp() As Boolean Dim CurrentProcesses As New ArrayList Dim ModuleName As String Dim ProcessName As String ModuleName = Process.GetCurrentProcess.MainModule.ModuleName ProcessName = Path.GetFileNameWithoutExtension(ModuleName) CurrentProcesses.Add(Process.GetProcessesByName(ProcessName)) Return CurrentProcesses.Count = 0 End Function |
| C# private bool ShouldRunApp() { ArrayList CurrentProcesses = new ArrayList(); string ModuleName; string ProcessName; ModuleName = Process.GetCurrentProcess().MainModule.ModuleName; ProcessName = Path.GetFileNameWithoutExtension(ModuleName); CurrentProcesses.Add(Process.GetProcessesByName(ProcessName)); //If it's zero, run it, if not don't do anything. return CurrentProcesses.Count == 0; } |