There could be a scenario where the application is running in a background process and the user tries to relaunch the application. In such a scenario, instead of showing a message to the user, you may want to activate the already running application and show its UI.
You can do this by changing a bit of the existing code and integrating an unmanaged code call. To do so, open the App.xaml.cs file once again and follow these steps:
- Add the following using namespace into the file: System.Runtime.InteropServices.
- Then, you need to add the following unmanaged code declaration from the user32.dll to the App.xaml.cs file:
[DllImport("user32", CharSet = CharSet.Unicode)] static extern IntPtr FindWindow(string cls, string win); [DllImport("user32")] static extern IntPtr SetForegroundWindow(IntPtr hWnd);
- Add the following method to activate the already running window, provided that the title of the window is static. In our case, it is Single Instance Demo, modified in the MainWindow.xaml page:
private static void ActivateWindow() { var otherWindow = FindWindow(null, "Single Instance Demo"); if (otherWindow != IntPtr.Zero) { SetForegroundWindow(otherWindow); } }
- Now, instead of calling the MessageBox, call the ActivateWindow() method in the OnStartup. Here, you can find this new 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!"); ActivateWindow(); Shutdown(); } }
- Now run the application. It will launch the MainWindow titled Single Instance Demo on the screen.
- Return to Visual Studio. This will put the application window in the background. Now run the application once again by pressing the keyboard shortcut CTRL + F5. This time, instead of running a different instance to show the UI, it will activate the existing window and push the running application to foreground.
It's not mandatory that the application window must always have a static title. In such cases, it will become more complex to handle said scenario.