简体   繁体   中英

How to close exit and restart program

I have a program and Im checking if there is an instance running, and if there is an instance running it should terminate the running program and run my app.. before I was just prompting the user that there is a running instance and just close the program. Now the user want the program to just terminate that instance and launch the app.

if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1)
{
 //MessageBox.Show("Another instance of the Program is Running", Global.ProgName, MessageBoxButton.OK, MessageBoxImage.Information);
 //Environment.Exit(0);
 foreach (var process in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)))
 {
    process.Kill();
 }
 Process.Start(Path.GetFileName(Assembly.GetEntryAssembly().Location));
}
if(Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1)
{
    foreach (var process in Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)))
    {
        if (process.Id != Process.GetCurrentProcess().Id)
        {
            process.Kill();
        }
    }
}

This code gets the processes which has same name with yours and kills the old ones, new one is the killer one.

在此处输入图像描述

It isn't clean, but you could use a shell command:

ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 127.0.0.1 -n 4 && cd \"" + Application.StartupPath + "\" &&  filename.exe";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
System.Timers.Timer t = new System.Timers.Timer(1000);
t.Elapsed += T_Elapsed;
t.Start();
Process.Start(Info);

private void T_Elapsed(object sender, ElapsedEventArgs e)
{
    Application.Exit();
}

The shell command pings localhost 4 times to pass time, and during those pings, the program exits. The original shell command is still running after the program exits, so the program re-opens after the pings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM