Single Instance Of Application In C#

Introduction

There is some application that we want that only a single instance of application works at a time. So here is the logic for doing that.

Here, I am getting a process list, and I check whether there is a process with the same name as the current process. If yes, then processes. length will be greater than one; then, we exit from the new instance.

Example

using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace Single_Instance
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            CheckInstance();
            // Perform your application procedures here.
        }
        private void CheckInstance()
        {
            Process[] thisNameProcessList;
            string moduleName, processName;
            Process currentProcess = Process.GetCurrentProcess();
            moduleName = currentProcess.MainModule.ModuleName.ToString();
            processName = System.IO.Path.GetFileNameWithoutExtension(moduleName);
            thisNameProcessList = Process.GetProcessesByName(processName);
            if (thisNameProcessList.Length > 1)
            {
                MessageBox.Show("Instance of this application is already running.");
                Application.Exit();
            }
        }
    }
}


Similar Articles