How to check if the program is already running in C#

Asked

Viewed 4,491 times

6

I wonder if there is a way to check if there is already an instance of the running program, so that if I click the program icon it does not call a new instance of the program but open the already active program. I need the code in C#.

  • Searching through the process does not help?

3 answers

8

You can also make use of Mutex
Obs: in the 2nd parameter (Name), I managed a GUID.

using System.Threading;


static class Program {

    static Mutex mutex = new Mutex(true, name: "{37BF258D-FA21-476C-9E6A-0FE832F984C2}");

    [STAThread]
    static void Main() {
        if (mutex.WaitOne(TimeSpan.Zero, true)) {
            try {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            finally {
                mutex.ReleaseMutex();
            }
        }
        else {
            MessageBox.Show("Este programa já está sendo executado!");
        }
    }
}
  • 4

    +1, This is the most accurate way. Applications may have the same executable name, but mutex (if the application can guarantee name uniqueness) will be unique.

  • 3

    I’ve had an ambiguity problem with the executable name. Never again after Mutex ;)

  • 2

    This is the correct way, the way above, does not work if the program is used on a windows terminal server.

6


Use the class Mutex. Processes can have equal names and this can get in the way. Especially in a context where there is no complete control of the destination station.

using System.Threading;    

class Program 
{
    // name é o identificador único da aplicação
    static Mutex _mutex = new Mutex(true, name: "d4709732-f5aa-404f-ba0e-a0a8a4201ff6");

    static void Main() 
    {
        if (_mutex.WaitOne(TimeSpan.Zero, true)) 
        {
            try 
            {
                InicializarAplicacao();
            }
            finally 
            {
                _mutex.ReleaseMutex();
            }
        }
        else 
        {
            MessageBox.Show("Já existe uma instancia do programa em execução");
        }
    }
}

By way of knowledge it is possible to search for the process with the same name of the current process. Remembering that this will cause problems if there is another process with the same name.

static void Main(string[] args)
{    
    Process processoAtual = Process.GetCurrentProcess();

    var processoRodando = (from proc in Process.GetProcesses()
                           where proc.Id != processoAtual.Id &&
                                 proc.ProcessName == processoAtual.ProcessName
                           select proc).FirstOrDefault();

    if (processoRodando != null)
    {
        MessageBox.Show("Já existe uma instancia do programa em execução");
        return; 
    }

    InicializarAplicacao();
}

Or

static void Main(string[] args)
{
    // Nome do processo atual
    string nomeProcesso = Process.GetCurrentProcess().ProcessName;

    // Obtém todos os processos com o nome do atual
    Process[] processes = Process.GetProcessesByName(nomeProcesso);

    // Maior do que 1, porque a instância atual também conta
    if (processes.Length > 1)
    {
        MessageBox.Show("Já existe uma instancia do programa em execução");  
        return;
    } 

    InicializarAplicacao();
}

3

 public partial class App : System.Windows.Application
    {
        public bool IsProcessOpen(string name)
        {
            foreach (Process clsProcess in Process.GetProcesses()) 
            {
                if (clsProcess.ProcessName.Contains(name))
                {
                    return true;
                }
            }

            return false;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            // Get Reference to the current Process
            Process thisProc = Process.GetCurrentProcess();

            if (IsProcessOpen("name of application.exe") == false)
            {
                //System.Windows.MessageBox.Show("Application not open!");
                //System.Windows.Application.Current.Shutdown();
            }
            else
            {
                // Check how many total processes have the same name as the current one
                if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
                {
                    // If ther is more than one, than it is already running.
                    System.Windows.MessageBox.Show("Application is already running.");
                    System.Windows.Application.Current.Shutdown();
                    return;
                }

                base.OnStartup(e);
            }
        }

Copy reply.

  • 1

    It would be interesting to add an explanation to your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.