How To Run A Single Instance Of Your Application

In some cases, we might have to run only a single instance of our application and restrict a user to running multiple instances of the application at a time (for example. Windows Media Player). This blog is applicable to both Windows Form and WPF Applications.
 
Getting Started
 
Step 1 

Create a class file named SingleInstance.cs in your project.
  1. public sealed class SingleInstance  
  2. {  
  3.        public static bool AlreadyRunning()  
  4.        {  
  5.            bool running = false;  
  6.            try  
  7.            {  
  8.                // Getting collection of process  
  9.                Process currentProcess = Process.GetCurrentProcess();  
  10.   
  11.                // Check with other process already running   
  12.                foreach (var p in Process.GetProcesses())  
  13.                {  
  14.                    if (p.Id != currentProcess.Id) // Check running process   
  15.                    {  
  16.                        if (p.ProcessName.Equals(currentProcess.ProcessName) == true)  
  17.                        {  
  18.                            running = true;  
  19.                            IntPtr hFound = p.MainWindowHandle;  
  20.                            if (User32API.IsIconic(hFound)) // If application is in ICONIC mode then  
  21.                                User32API.ShowWindow(hFound, User32API.SW_RESTORE);  
  22.                            User32API.SetForegroundWindow(hFound); // Activate the window, if process is already running  
  23.                            break;  
  24.                        }  
  25.                    }  
  26.                }  
  27.            }  
  28.            catch { }  
  29.            return running;  
  30.        }  
NOTE

SingleInstance class has been declared sealed to avoid memory leakage. 
 
To set the running process to the foreground, we have to use the functions availabe in User32.dll

We are creating another class i.e. UserAPI class.

Step2

Create a class file named User32API.cs. 
  1. using System.Runtime.InteropServices;  
  2. public class User32API    
  3.     {    
  4.         [DllImport("User32.dll")]    
  5.         public static extern bool IsIconic(IntPtr hWnd);    
  6.     
  7.         [DllImport("User32.dll")]    
  8.         public static extern bool SetForegroundWindow(IntPtr hWnd);    
  9.     
  10.         [DllImport("User32.dll")]    
  11.         public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);    
  12.     
  13.         public const int SW_RESTORE = 9;    
  14.     }  
Step 3 

Implement this in our application.
 
In WPF 

Open App.xaml.cs (under App.xaml) from the Solution Explorer and overriding the OnStartup method. 
  1. protected override void OnStartup(StartupEventArgs e)  
  2. {  
  3.     if (SingleInstance.AlreadyRunning())  
  4.         App.Current.Shutdown(); // Just shutdown the current application,if any instance found.  
  5.       
  6.     base.OnStartup(e);  
  7. }  
In Windows Form

Open Program.cs from Solution Explorer and modify the snippet. 
  1. static class Program  
  2.     {  
  3.         /// <summary>  
  4.         /// The main entry point for the application.  
  5.         /// </summary>  
  6.         [STAThread]  
  7.         static void Main()  
  8.         {  
  9.             Application.EnableVisualStyles();  
  10.             Application.SetCompatibleTextRenderingDefault(false);  
  11.                           
  12.                         // Allow the application to run your application, if no any instance running  
  13.                         if(!SingleInstance.AlreadyRunning())              
  14.                             Application.Run(new Form1());  
  15.         }  
  16.     }   
Conclusion

Implementing two classes in our Application restricts the user to allowing multiple instances.
 
I hope, you enjoyed reading this blog. Stay connected to C# Corner for more updates.