Preventing Multiple instances of the same application

June 12th, 2007 by Chris

As many programmers have come across, sometimes you want to prevent your app being launched more than once. This is a desirable function for many reasons. This can be used when you're app relies on writing or reading from files, and to prevent locking of files and possible corruption, you only want your app to run once. If you're writing something that is going to be only useful in a single instance, you can check and prevent multiple instances being run. The code snippet below details how to perform this check at the launch of your app.


C#:
  1. using System;
  2. using System.Windows.Forms;
  3. public partial class MainDesktop : System.Windows.Window
  4. {
  5.     public MainDesktop()
  6.     {
  7.         if (System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length == 1)
  8.         {
  9.             /// App initilization code here
  10.         }
  11.         else
  12.         {
  13.             this.Close();
  14.         }
  15.     }
  16. }

Put this code in the main method of your app. This way when it runs, it checks and if finds another process with the same name, causes the new app to close instantly.

Technorati Tags: , ,

Posted in Windows Forms |

One Response

  1. Andre Ranieri Says:

    Is System.Diagnostics.Process scoped globally across the local machine or is it specific to the current user session?

    I’m asking because developers working on terminal services friendly applications may not be able to use this method if it applies globally to the entire computer.

    Andre Ranieri

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.