Application-Running-already-WPF

Is Application running already in WPF

Is Application running already in WPF

Hello folks, till now we have already discussed regarding different topics like WPF The calling thread cannot access this object because a different thread owns it, which is very important when you want to update your UI stuffs while thread is running or from thread, and you have also read Extension Method in C#Extension Method with parameter in C#Reflection Introduction c#,  Reflection with Property in C#The Microsoft Jet database engine cannot open the file. It is already opened exclusively by another user.

Today, we will look into very important concept, lets say we have developed windows application or WPF application and if we haven’t check for whether application is running or not already, our application could open multiple times. Have look into below image.

Is-Application-Running-already-Without-Check
Is-Application-Running-already-Without-Check

Lets try put check on it, “Is Application running already in WPF”.

Solution:

To put check we need to get current process name and then try to fetch all the processes running in the task manager and at last find whether more than one instance is running or not.  Below is code snippet for checking.

using System.Windows;
using System.Diagnostics;

namespace IsApplicationRunning
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            CheckForIsRunningApplication();
        }
        private void CheckForIsRunningApplication()
        {
            //Get Current Process Name
            string strProcessName = Process.GetCurrentProcess().ProcessName;

            //Get All the running processes with same name
            Process[] strAllProcesses = Process.GetProcessesByName(strProcessName);

            //If process exists in task manager, kill current process with show message
            if (strAllProcesses.Length > 1)
            {
                MessageBox.Show("Application is already running.");
                Application.Current.Shutdown();
            }
        }
    }
}

Now build application and try to run multiple times this application, you will get below output.

Is-Application-Running-already-WPF
Is-Application-Running-already

You could also download sample example of Is Application running already in WPF

Leave a Reply