Running only 1 application instance in a machine

A

anonieko

Avoid running several simultaneous instances of the same application on
a single machine. ( Checking if application is already running)

(Book Excerpt Practical C#2)

Thanks to the static methods named GetCurrentProcess() (which returns
the current
process) and GetProcesses() (which returns all the processes on the
machine) of the System.
Diagnostics.Process class, this problem finds an elegant and easy to
implement solution using
the following program:


using System.Diagnostics;

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (TestIfAlreadyRunning())
{
MessageBox.Show("Application is already running");
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}

static bool TestIfAlreadyRunning()
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
if (process.Id != currentProcess.Id)
if (process.ProcessName ==
currentProcess.ProcessName)
return true;
}
return false;
}
}
The GetProcesses() method can also return all the processes on a remote
machine by indicating the name of the machine as a parameter to the
method.
 
M

Michael Nemtsev

And what if user decided to rename app to call one more instance? :)
Why not to use Global mutext.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top