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

6

I would like to know if there is a way to check if a program instance is already running, so in case 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 #.

    
asked by anonymous 19.04.2017 / 16:17

3 answers

5

Use the Mutex class. . Processes can have equal names and this can get in the way. Especially in a context where one does not have 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 you can search for the process with the same name as the current process. Remembering 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();
}
    
19.04.2017 / 16:25
8

You can also use Mutex
Note: In the 2nd parameter ( Name ), I generated 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!");
        }
    }
}
    
19.04.2017 / 16:36
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 Response

    
19.04.2017 / 16:26