using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Windows; namespace FLY.AppHelper { public class AppJustOne { public AppJustOne(Application app) { app.Startup += new StartupEventHandler(app_Startup); } void app_Startup(object sender, StartupEventArgs e) { Process process = Process.GetCurrentProcess(); string name = process.ProcessName; Process[] processes = Process.GetProcesses(); IEnumerable<Process> ps = from p in processes where (p.ProcessName == process.ProcessName) && (p.Id != process.Id) && (p.MainModule.FileName == process.MainModule.FileName) && (p.HasExited) select p; try { if (ps.Count() >= 1) { MessageBoxResult r = MessageBox.Show(name + "已经运行, 是否关闭正在运行的,然后重启新的?", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No); if (r == MessageBoxResult.Yes) { for (int i = 0; i < ps.Count(); i++) { Process p = ps.ElementAt(i); p.Kill(); } } else { System.Environment.Exit(0); } } } catch { //当有进程正在关闭时,访问ps 就会出错 } } } }