Thursday, March 22, 2012

WPF (C#) : Make sure only one instance of your application is running

In this article I am going to show how to figure out if your application is already running and you don't want to start a new instance of application.
I am going to write this method in Application_Startup event in WPF, but this logic can be used in Winforms also.

In Your Application_Startup , Check if there is already a process running which has same name like your process and if yes then that means application is already running and exit.

Here is sample App.xaml.cs file


public partial class App : Application
    {
        #region Variables
        bool alreadyloggedin = false;
        #endregion
 
        #region Events
 
 
        private void Application_Startup(object sender, StartupEventArgs e)
        {
 
            Process[] processlist = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
            alreadyloggedin = processlist.Length > 1;
 
          
 
            if (alreadyloggedin)
            {
                MessageBox.Show("Application is already running");
                App.Current.Shutdown();
                return;
            }
 
            
        }
 
       
 
        #endregion
    }

No comments:

Post a Comment