繁体   English   中英

如何关闭退出并重新启动程序

[英]How to close exit and restart program

我有一个程序,我正在检查是否有一个实例正在运行,如果有一个实例正在运行,它应该终止正在运行的程序并运行我的应用程序。在我只是提示用户有一个正在运行的实例并关闭之前程序。 现在用户希望程序终止该实例并启动应用程序。

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();
        }
    }
}

此代码获取与您的同名进程并杀死旧进程,新进程是杀手进程。

在此处输入图像描述

它不干净,但您可以使用 shell 命令:

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();
}

shell 命令 ping localhost 4 次以消磨时间,在这些 ping 期间,程序退出。 程序退出后,原来的 shell 命令还在运行,所以程序在 ping 后重新打开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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