0
我試圖檢查,當程序啓動時,如果一個實例曾經啓動。如果是這樣,我想殺死它。不同的進程句柄
我有這樣的代碼:
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個進程處理,在檢查的過程中是我的程序實例,手柄是不同的。
你可以通過Id比較它們而不是Handle嗎? – qbik
它的工作原理!我在想手柄比較好... – Veriditas