Single instance of application in C#


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

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace Single_Instance
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            checkinstance();
            // now you can do your application proceduren
        }
        public void checkinstance()
        {
            Process[] thisnameprocesslist;
            string modulename, processname;
            Process p = Process.GetCurrentProcess();
            modulename = p.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();
            }
        }
    }
}

Up Next
    Ebook Download
    View all
    Learn
    View all