簡體   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