如何运行应用程序的一些方法和功能自动重启后
How do I run some methods and functions of an application after restarting the application automatically
我有一个 C# 应用程序,有时我需要重新启动我的应用程序,然后,我需要 运行 一些命令并更改我的 C# 应用程序的一些变量。
我从以下代码重新启动我的应用程序:
Application.Restart();
Environment.Exit(0);
退出后运行需要在此处插入一些代码
您可以在应用程序设置中创建一个标志,然后在启动时处理它:
//Set a flag on restart
Properties.Settings.Default.IsRestarting = true;
Properties.Settings.Default.Save();
Application.Restart();
...
//Process it on startup (e.g. Main method or Form.Load event for the main form)
if(Properties.Settings.Default.IsRestarting)
{
// run some commands and change some variables here
Properties.Settings.Default.IsRestarting = false;
Properties.Settings.Default.Save();
}
或者,您可以将此标志存储在任何您想要的位置:文件系统、注册表、数据库等。
您还可以使用 Process.Start
而不是 Application.Restart
来 运行 您应用的另一个实例。通过这种方式,您可以与新进程进行交互:发送命令行参数、传递消息。
另见:Why is Application.Restart() not reliable?
我有一个 C# 应用程序,有时我需要重新启动我的应用程序,然后,我需要 运行 一些命令并更改我的 C# 应用程序的一些变量。 我从以下代码重新启动我的应用程序:
Application.Restart();
Environment.Exit(0);
退出后运行需要在此处插入一些代码
您可以在应用程序设置中创建一个标志,然后在启动时处理它:
//Set a flag on restart
Properties.Settings.Default.IsRestarting = true;
Properties.Settings.Default.Save();
Application.Restart();
...
//Process it on startup (e.g. Main method or Form.Load event for the main form)
if(Properties.Settings.Default.IsRestarting)
{
// run some commands and change some variables here
Properties.Settings.Default.IsRestarting = false;
Properties.Settings.Default.Save();
}
或者,您可以将此标志存储在任何您想要的位置:文件系统、注册表、数据库等。
您还可以使用 Process.Start
而不是 Application.Restart
来 运行 您应用的另一个实例。通过这种方式,您可以与新进程进行交互:发送命令行参数、传递消息。
另见:Why is Application.Restart() not reliable?