AppJustOne.cs 1.91 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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) &&
潘栩锋's avatar
潘栩锋 committed
28
                                          (!p.HasExited)
潘栩锋's avatar
潘栩锋 committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
                                      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 就会出错
            }
        }
    }
}