Single WPF Application Instance

2014-01-05


How we force to run only one instance of our WPF application ?

There were different solutions on internet. here we collect some of them.

1: Solution 1:

If you are using higher versions of .NET, you will find checking process name is very easy solution to get single WPF application instance.

In your App.xaml.cs, add the following code:

_protected override void OnStartup(StartupEventArgs e)     
{      
    Process thisProc = Process.GetCurrentProcess();      
    if (Process.GetProcessesByName(thisProc.ProcessName).Length >1)      
    {      
        MessageBox.Show("Application is already running.");      
        Application.Current.Shutdown();      
        return;      
    }_
  
_    base.OnStartup(e);     
}_
 

That’s it! very easy.

2: Solution 2:

using Mutex class.

Actually, using Mutex class is not only working for WPF applications, but also working for other type solutions such as Windows Form application.

Still in App.xaml.cs file, add the following code

_private Mutex theMutex = null;_
  
_protected override void OnStartup(StartupEventArgs e)     
{      
    bool retV;      
    theMutex = new Mutex(true, "{MyApp-mystring-12345676-dajkfdac-My_App_Unistring}", out retV);_
  
_    if (!retV)     
    {      
        MessageBox.Show("Application is already running.");      
        theMutex = null;      
        Application.Current.Shutdown();      
        return;      
    }_
  
_    base.OnStartup(e);     
}_
  
_protected override void OnExit(ExitEventArgs e)     
{      
    if (theMutex != null)      
        theMutex.ReleaseMutex();      
    base.OnExit(e);      
}      
_

3: Solution 3:

See Microsoft’s Single Instance Detection Sample