Question

Is it possible for a WPF application to check if any other instances of the application are running? I'm creating an application that should only have one instance, and will prompt a message that "another instance is running" when the user tries to open it again.

I'm guessing I'd have to check through the process logs to match my application's name, but I'm not sure how to go about doing that.

Was it helpful?

Solution

The get processes by name strategy can fail if the exe has been copied and renamed. Debugging can also be problematic because .vshost is appended to the process name.

To create a single instance application in WPF, you can start by removing the StartupUri attribute from the App.Xaml file so that it looks like this...

<Application x:Class="SingleInstance.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Application>

After that, you can go to the App.xaml.cs file and change it so it looks like this...

public partial class App 
{
    // give the mutex a  unique name
    private const string MutexName = "##||ThisApp||##";
    // declare the mutex
    private readonly Mutex _mutex;
    // overload the constructor
    bool createdNew;
    public App() 
    {
        // overloaded mutex constructor which outs a boolean
        // telling if the mutex is new or not.
        // see http://msdn.microsoft.com/en-us/library/System.Threading.Mutex.aspx
        _mutex = new Mutex(true, MutexName, out createdNew);
        if (!createdNew)
        {
            // if the mutex already exists, notify and quit
            MessageBox.Show("This program is already running");
            Application.Current.Shutdown(0);
        }
    }
    protected override void OnStartup(StartupEventArgs e)
    {
        if (!createdNew) return;
        // overload the OnStartup so that the main window 
        // is constructed and visible
        MainWindow mw = new MainWindow();
        mw.Show();
    }
}

This will test if the mutex exists and if it does exist, the app will display a message and quit. Otherwise the application will be constructed and the OnStartup override will be called.

Depending upon your version of Windows, raising the message box will also push the existing instance to the top of the Z order. If not you can ask another question about bringing a window to the top.

There are additional features in the Win32Api that will help further customize the behaviour.

This approach gives you the message notification you were after and assures that only one instance of the main window is ever created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top