You're looking for the Mutex
Class. It's pretty complicated, but luckily the Singleton Pattern has been widely discussed. There are several good articles on it, but you can find a good implementation of it in the C# .NET Single Instance Application page on the Sanity Free Coding website. From the linked page:
static class Program {
static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
[STAThread]
static void Main() {
if(mutex.WaitOne(TimeSpan.Zero, true)) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
mutex.ReleaseMutex();
} else {
MessageBox.Show("only one instance at a time");
}
}
}
Now you're probably wondering how to have a Main
method in a WPF Application, right? Well there's a few things that you have to do, but it's not difficult. See the Writing a custom Main() method for WPF applications article which explains this in detail. From that article:
You basically need to change the application’s build action from “Application Definition” to “Page”, create a constructor that calls “InitializeComponent”, and write your Main() by eventually calling one of the application’s “Run” method overloads. ... Don’t forget, also, to remove the “StartupUri” from the App.xaml, otherwise another copy of window will show up (unless you get an error because the URI points to a non existing XAML resource).
So by amalgamating these two resources, we can see that your App.xaml.cs
file should look something like this:
public partial class App : Application
{
private static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
private static MainWindow mainWindow = null;
App()
{
InitializeComponent();
}
[STAThread]
static void Main()
{
if(mutex.WaitOne(TimeSpan.Zero, true))
{
App app = new App();
mainWindow = new MainWindow();
app.Run(mainWindow);
mutex.ReleaseMutex();
}
else
{
mainWindow.WindowState = WindowState.Normal;
}
}
}