Skip to content

Instantly share code, notes, and snippets.

@tecnocrata
Created February 19, 2014 21:53
Show Gist options
  • Select an option

  • Save tecnocrata/9102457 to your computer and use it in GitHub Desktop.

Select an option

Save tecnocrata/9102457 to your computer and use it in GitHub Desktop.
Single Instance of WPF Application
First 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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment