Single instance per user of desktop application (.NET)

Here is the code to restrict a desktop application to single instance per user (for single instance desktop application follow the link).

The example here makes use of MUTEX to restrict the number of instances.

static void Main(string[] args)
{
            String mutexName = "MyApplication" +
            System.Security.Principal.WindowsIdentity.GetCurrent().User.AccountDomainSid;

            Boolean createdNew;

            Mutex mutex = new Mutex(true, mutexName, out createdNew);

            if (!createdNew)
            {
                //If createdNew is false that means an instance of application is already running for this  
                // user.
                //So in this case stop the application from executing.
                return;
            }
            Console.ReadKey();
 }

In the above example replace MyApplication with your application name.

In this example we have created a Mutex named mutex, in the constructor we have supplied three arguments these are :-

     1.) initiallyOwned true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

      2.) name  - It is the name of the mutex. In our case the name of mutex is very important as we control the number of instances of the application using the mutex name. As you might have noticed I have used both the application name and current user's SID to create the mutex name so that the name remains unique for the application and current user. Thus the mutex name will be different for each user and we can have one instance of the application for each user.

      3 .) createdNew - This argument is of out type. If the output to this parameter is true that means the mutex was not already created and it is created by this call, this implies that this is the first instance of the application for this user so we can allow it to execute further. But, if the output is false this means an instance of the application is already running for this user, so in the case stop the application from executing further

For more information about Mutex class follow the link.

Similarly we can restrict the application to only one instance for the whole system, for that just remove the SID part from the mutex name and use only the application name for the mutex name or you can also use a hard coded string as the mutex name in this case, for more info follow the link.

No comments:

Post a Comment