Once the WPF project has been created, follow these steps to create a single instance of the WPF application:
- Run the application by pressing the CTRL + F5 key combination. This will launch one instance of the application.
- Press CTRL + F5 multiple times to launch multiple instances of the application. Now it's time to make the application a single instance application:
- Close all the running processes and then follow the next steps to implement the single instance behavior.
- Open the MainWindow.xaml and add the window title to Single Instance Demo. Here you can find the entire XAML code:
<Window x:Class="CH01.SingleInstanceDemo.MainWindow" xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Single Instance Demo" Height="250" Width="400"> <Grid> </Grid> </Window>
- Open the App.xaml.cs file and override the base implementation of the OnStartup method.
- Change the code of the OnStartup method so that it looks like the following code:
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var mutex = new Mutex(true, "SingleInstanceDemo", out bool isNewInstance); if (!isNewInstance) { MessageBox.Show("Application instance is already running!"); Shutdown(); } }
- Add the System.Threading namespace declaration, so that the Mutex can be discoverable. The Mutex resides in the aforesaid namespace.
- Now compile the project to make sure that there are no compiler errors.
- Press CTRL + F5, which will run the first instance of the application.
- Now return to the Visual Studio, without closing the application, and then hit CTRL + F5. This time, instead of launching the application UI, an Application instance is already running! message will pop up on the screen. Clicking OK will close the message.
- Press CTRL + F5 again. Observe that no second instance of the UI is visible on the screen.