Dot Net For All

Create a single instance WPF application

Single Instance Applications

There are many chances while working on the WPF applications we need to have only a single instance of the application active as a single process. How to create a single instance Create a single instance WPF application and which in turn should be activated as soon user tries to create another instance.

Usually whenever we execute an .exe, every time it creates a separate windows process with its own address space, resources and so on.  But we do not want this criteria as this would prevent us from creating single process. In this article I will take you through the steps to create a single process application and whenever that application is running in background, it should come to the main screen.

Sample Application –

First of all I will take you through the process of creating a single instance application followed by the explanation of what is happening in the application.

  1. Create a WPF Project by navigating to File > New > Project

 

2. Give a name to the main window as shown below

<Window x:Class="SingleInstanceWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="OnlySingle" Height="350" Width="525">
    <Grid>
        
    </Grid>
</Window>

3. Use the following user32 dll’s functions in App.xaml.cs

        [DllImport("user32", CharSet = CharSet.Unicode)]
        static extern IntPtr FindWindow(string cls, string win);
        [DllImport("user32")]
        static extern IntPtr SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32")]
        static extern bool IsIconic(IntPtr hWnd);
        [DllImport("user32")]
        static extern bool OpenIcon(IntPtr hWnd);

4. Open the App.xaml.cs file and add the following references

using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

and override the OnStartUp method as shown below

 protected override void OnStartup(StartupEventArgs e)
        {
            bool isNew;
            var mutex = new Mutex(true, "MyWindowsMutext", out isNew);
            if (!isNew)
            {
                ActivateOtherWindow();
                Shutdown();
            }
        }

        private static void ActivateOtherWindow()
        {
            var other = FindWindow(null, "OnlySingle");
            if (other != IntPtr.Zero)
            {
                SetForegroundWindow(other);
                if (IsIconic(other))
                    OpenIcon(other);
            }
        }

5. Now try running (ctrl + F5) the Visual Studio application. One the application is up. Try once more to run the application. We can see that it did not create a new instance of the application; instead it just bought the initially started application to the foreground.

What’s Happening Here 

In this example we have used Mutex which is a synchronization object, which in turn is used to synchronize access to a shared resource, so that one thread can access the resource at a time, thus preventing data corruption or other inconsistencies within shared resource. It wraps a win32 Mutex object(handle), so it’s true kernel object, capable of cross AppDomain and cross process synchronization which Monitor.Enter/Exit(or lock) cannot do.

 

Here Mutex constructor takes first parameter as Boolean which is used to verify if the calling thread is the owner of this Mutex, a string which is the name of the mutex, and an out param which is used to find if the calling thread is granted the owner ship of the mutex.

You can find about Mutex here on MSDN blog.

Also there can be chances that the Window which we have created does not have a constant name unlike our case. Suppose instead of the Title as “Only Single” suppose the title is “Only Single – Text.txt”, in this particular case it is difficult to implement our code. For that we can use win32 EnumWindows function, which would further help us to go over each top level window looking for the title and match to the expected pattern. The implementation for the EnumFunction can be found here in one of SO answer.

 

Please find the sample application code attached with the blog

 

 

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview