KnowDotNet NetRefactor

A Brief Introduction to the Process Class

by William Ryan
Print this Article Discuss in Forums

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;



Since DataSource can use anything that implements the IList interface, and ArrayLists do implement IList, you can bind the combox directly to it.  This saves you from having to walk the array/arraylist and load the combo box.

Enough of that though, let's use what we just did and check to see if the process that's the name of our app is existent.  If it is, we'll want to notify the user and respond accordingly - that's up to you:

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;
}


This is really simple stuff, but there's a couple of things you may find cool.  For one thing, it illustrates the Path Class and its GetFileNameWithoutExtension shared method.  It returns the name of the file without the extension on it.  This will save you from having to parse it out (Conversely, the class can give you the extension of a given file which is pretty cool when you are walking directories).  It also illustrates the GetProcessByName method that returns just one value instead of all current processes.  Finally, it uses GetCurrentProcess which not surprisingly returns the current process.  Combine a few of these together and you can do some cool things.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing