Single instance WPF application in C#

Update: 12/03/2012

I ran into some issues with the approach that I linked to below, and would not recommend it. It turns out that the best way to deal with this issue, is to use the Visual Basic instance detection classes (yes you can use these from C#). The sample code is available here

Note that is is more than likely that you will be retrofitting this to an existing project. If that is the case, make sure you double click the properties pane in visual studio and set your custom start-up file/class as shown below



Original Post

Keeping in the same vein as my previous post, I frequently find that I have to solve the same problems at times. After a year or several months I usually move onto another project, consequently no longer have the source code, so I am posting this as a bit of a sticky as I am sure someone will find it useful.

Visual Basic has single instance classes one can use, one can import these into any C# application and consume them (that, after all,  is the real beauty of .NET), but I found that there was too much code, and too many classes, and it was taking me too long a little while back. I solve this problem using the Process class. Create a WPF application and use as follows;

using System.Diagnostics;
using System.Linq;
using System.Windows;
namespace SingleInstanceApp
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
protected override void OnStartup(StartupEventArgs e)
private static void IsAppAlreadyRunning()
Process currentProcess = Process.GetCurrentProcess();
if (Process.GetProcessesByName(currentProcess.ProcessName).Any(p => p.Id != currentProcess.Id))
MessageBox.Show("Another instance is already running.", "Application already running",
MessageBoxButton.OK, MessageBoxImage.Exclamation);

One thought on “Single instance WPF application in C#

  1. I have fun with, result in I discovered just what I
    was looking for. You’ve ended my four day long hunt!
    God Bless you man. Have a nice day. Bye

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s