所以我创建了一个程序(不使用表单),所以它是一个干净的类,而不是表单。 因此,当程序启动时,我希望它检查进程,如果发现另一个进程,则自行终止。我试过这个...
static void checkDupe()
{
string RunningProcess = Process.GetCurrentProcess().ProcessName;
Process[] processes = Process.GetProcessesByName(RunningProcess);
if (processes.Length > 1)
{
Process.GetCurrentProcess().Kill();
}
}
请您参考如下方法:
看看使用 Mutex :
class Program
{
static Mutex _m;
static bool IsSingleInstance()
{
try
{
// Try to open existing mutex.
Mutex.OpenExisting("PERL");
}
catch
{
// If exception occurred, there is no such mutex.
Program._m = new Mutex(true, "PERL");
// Only one instance.
return true;
}
// More than one instance.
return false;
}
static void Main()
{
if (!Program.IsSingleInstance())
{
Console.WriteLine("More than one instance"); // Exit program.
}
else
{
Console.WriteLine("One instance"); // Continue with program.
}
// Stay open.
Console.ReadLine();
}
}
以上例子摘自:
