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.
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.