我正在尝试检查程序启动时是否启动实例。如果是的话,我想杀了它。
我有这段代码:
Process[] processes =
Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location));
while (processes.Length != 0)
{
bool killed = false;
foreach (Process process in processes)
{
string fileName;
try
{
fileName = process.Modules[0].FileName;
}
catch (Win32Exception)
{
continue;
}
if ((fileName == Assembly.GetExecutingAssembly().Location)
&& (process.Handle != Process.GetCurrentProcess().Handle))
{
MessageBox.Show("Test");
process.Kill();
Thread.Sleep(500);
killed = true;
MessageBox.Show("Test");
}
}
if (!killed)
break;
processes =
Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location));
}
唯一的问题是,当我比较2个进程句柄时,当检查的进程是我的程序实例时,句柄是不同的。
答案 0 :(得分:2)
按Id而不是Handle比较流程。