Nice programing

WPF 애플리케이션을 다시 시작하려면 어떻게해야합니까?

nicepro 2020. 10. 18. 19:35
반응형

WPF 애플리케이션을 다시 시작하려면 어떻게해야합니까?


WPF 애플리케이션을 다시 시작하려면 어떻게해야합니까? 내가 사용한 Windows Forms에서

System.Windows.Forms.Application.Restart();

WPF에서 어떻게하나요?


나는 이것을 발견했다 : 그것은 작동한다. 그러나. 더 좋은 방법이 있습니까?

System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
Application.Current.Shutdown();

나는 이것을 WPF에서 성공적으로 사용했습니다.

System.Windows.Forms.Application.Restart();
System.Windows.Application.Current.Shutdown();

Application.Restart();

또는

System.Diagnostics.Process.Start(Application.ExecutablePath);
Application.Exit();

내 프로그램에는 컴퓨터에서 실행되는 응용 프로그램의 인스턴스를 하나만 보장하는 뮤텍스가 있습니다. 이로 인해 뮤텍스가 적시에 릴리스되지 않았기 때문에 새로 시작된 응용 프로그램이 시작되지 않았습니다. 결과적으로 응용 프로그램이 다시 시작됨을 나타내는 값을 Properties.Settings에 입력했습니다. Application.Restart ()를 호출하기 전에 Properties.Settings 값이 true로 설정됩니다. Program.Main ()에서 특정 property.settings 값에 대한 검사를 추가하여 true 일 때 false로 재설정되고 Thread.Sleep (3000);

프로그램에는 다음과 같은 논리가있을 수 있습니다.

if (ShouldRestartApp)
{
   Properties.Settings.Default.IsRestarting = true;
   Properties.Settings.Default.Save();
   Application.Restart();
}

Program.Main ()에서

[STAThread]
static void Main()
{
   Mutex runOnce = null;

   if (Properties.Settings.Default.IsRestarting)
   {
      Properties.Settings.Default.IsRestarting = false;
      Properties.Settings.Default.Save();
      Thread.Sleep(3000);
   }

   try
   {
      runOnce = new Mutex(true, "SOME_MUTEX_NAME");

      if (runOnce.WaitOne(TimeSpan.Zero))
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new Form1());
      }
   }
   finally
   {
      if (null != runOnce)
         runOnce.Close();
   }
}

그게 다야.


Runs a new instance of the program by command line after 1 second delay. During the delay current instance shutdown.

ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C choice /C Y /N /D Y /T 1 & START \"\" \"" + Assembly.GetEntryAssembly().Location + "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
Process.GetCurrentProcess().Kill();

EDIT:

I fixed the code:

instead of: Assembly.GetExecutingAssembly().Location

this: Assembly.GetEntryAssembly().Location

This is important when the function runs in a separate dll.

And -

instead of: Application.Current.Shutdown();

this: Process.GetCurrentProcess().Kill();

It will work both in WinForms and in WPF and if you write a dll that is designed for both then it is very important.


Application.Current.Shutdown();
System.Windows.Forms.Application.Restart();

In this order worked for me, the other way around just started another instance of the app.


These proposed solutions may work, but as another commenter has mentioned, they feel kind of like a quick hack. Another way of doing this which feels a little cleaner is to run a batch file which includes a delay (e.g. 5 seconds) to wait for the current (closing) application to terminate.

This prevents the two application instances from being open at the same time. In my case its invalid for two application instances to be open at the same time - I'm using a mutex to ensure there is only one application open - due to the application using some hardware resources.

Example windows batch file ("restart.bat"):

sleep 5
start "" "C:\Dev\MyApplication.exe"

And in the WPF application, add this code:

// Launch the restart batch file
Process.Start(@"C:\Dev\restart.bat");

// Close the current application
Application.Current.MainWindow.Close();

 Application.Restart();
 Process.GetCurrentProcess().Kill();

work like a charm for me


Taking Hooch's example, I used the following:

using System.Runtime.CompilerServices;

private void RestartMyApp([CallerMemberName] string callerName = "")
{
    Application.Current.Exit += (s, e) =>
    {
        const string allowedCallingMethod = "ButtonBase_OnClick"; // todo: Set your calling method here

        if (callerName == allowedCallingMethod)
        {
            Process.Start(Application.ResourceAssembly.Location);
        }
     };

     Application.Current.Shutdown(); // Environment.Exit(0); would also suffice 
}

참고URL : https://stackoverflow.com/questions/4773632/how-do-i-restart-a-wpf-application

반응형