Monday, August 12, 2013

WPF–Creating a single instance application

I wanted to make my WPF application such that only a single instance of it could run at a time. I found that there were 2 main ways demonstrated on the internet:
1. Use “Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase” and setup the “OnStartupNextInstance” to activate the first instance of the application. or
2. Use Mutex to ensure only a single instance of a program can be run at time. (Which is the accepted answer on StackOverflow. http://stackoverflow.com/a/522874/44815).
I wanted to use the Mutex method, though the article referenced in the StackOverflow answer - “C# .Net Single Instance Application” does not give all the details that one has to implement for a WPF application, so here is some more detailed info:

1. Add a Mutex to the “App” class
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
 /// <summary>
 /// This should be a unique name which is used to determine if another instance of app is running
 /// </summary>
 private const string APP_UNIQUE_NAME = "UNIQUENAME_FOR_MY_APP or use a GUID";
  /// <summary>
  /// Initializes the Mutex class and make the calling thread have initial ownership of the mutex
 /// and a string that is the name of the mutex.
 /// </summary>
 static readonly Mutex _mutex = new Mutex(true, APP_UNIQUE_NAME);


2. Add a Main method to the “App” class, which will act as the entry point for the application and will signal the mutex to wait until its released
[STAThread]
static void Main()
{
//using TimeSpan.Zero as we want the mutex to test state of wait handle and return immediately
 if (_mutex.WaitOne(TimeSpan.Zero, true))
 {
 //calling waitone stops everyone else from entering the code in this block until the mutex is released
  try
  {
   App app = new App();
   app.InitializeComponent();
   app.Run();
  }
  finally
  {
   _mutex.ReleaseMutex(); 
  }
 }
 else
 {
  MessageBox.Show("Only one instance of the app can be run!","App Name",MessageBoxButton.OK, MessageBoxImage.Exclamation);
 }
}
3. Setup the WPF application to use the “Main” method as its entry point
a. Right click on the application’s project file and select properties. On the tab “Application”, set the “Startup object” to the name of the “App” class we modified above.
b. Right click on the “App.xaml” file in your project and select properties. Change the “Build Action” to “Page” from “ApplicationDefinition
4. Build and test the application!

No comments: