In this article, i will show you a method which determines if the program is already running. I get with System.Diagnostics.Process.GetCurrentProcess().ProcessName the process name of the current program. string strCurrentProcess = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
I identify how many instances of the program are already running.
System.Diagnostics.Process.GetProcessesByName(strCurrentProcess).Length
If they are more than one, then a message is show to the user.
if (System.Diagnostics.Process.GetProcessesByName(strCurrentProcess).Length > 1)
{
Console.WriteLine("Another instance of this program is already running.");
...
}
The code itself is listed below.
using System;
namespace ConsoleApplication1
{
class Class1 {
[STAThread]
static void Main(string[] args)
{
string strCurrentProcess = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
if (System.Diagnostics.Process.GetProcessesByName(strCurrentProcess).Length > 1)
{
Console.WriteLine("Another instance of this program is already running.");
Console.ReadLine(); return;
}
else
{
Console.WriteLine("No another instance of this program is running.");
Console.ReadLine();
}
}
}
}
Özgür Aytekin (MCSD .NET, MCDBA) www.dotnetcracks.com
|