系统重启后恢复C#应用程序

时间:2014-01-10 11:35:10

标签: c# wpf

我写了一个简单的c#wpf代码,如下所示,

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    }
   private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        label1.Content = "Before restart";
        System.Diagnostics.Process.Start("ShutDown", "-r"); //restart
        label2.Content = "After restart";

    }

}

现在问题是我想在重启后自动恢复我的应用程序,并将消息显示为“重启后”。请帮我解决这个问题...

3 个答案:

答案 0 :(得分:2)

此问题的解决方案是将状态保持在硬盘或某些永久性内存(如自定义事务文件)中。

例如

申请中会有不同的阶段。我将在处理成文件后进入每个阶段。一台机器停止,然后如果应用程序自动启动,它将从该文件读取该阶段,然后从该阶段进行处理。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    //Read stage from transaction file as **Stage**
    if(Stage == Stage1)
    {
        label1.Content = "Before restart";
        WriteTransaction(Stage2);
    }
    System.Diagnostics.Process.Start("ShutDown", "-r"); //restart
    if(Stage == Stage2)
    {
        label2.Content = "After restart";
        //Finish transaction and delete the transaction file.
    }

}

这样你就可以解决问题了。

要自动重启应用程序,您可以将可执行文件放在启动文件夹下,甚至可以将其视为Windows服务。

答案 1 :(得分:0)

这是一个概念(伪代码):

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    // initialize defaults
    bool isRestarted = false;
    label1.Content = "";
    label2.Content = "";

    // Check the state
    if (stateFile.Exists) // stateFile is something like type FileInfo
    {
        var text = File.ReadAllText(stateFile.FullName);
        isRestarted = ParseForBool(text);
        label1.Content = ParseForLabel(text); // if you want that to be restored as well
    }

    if (isRestarted)
    {
        label2.Content = "After restart";
        DoSomeMagicRemoveAutostart(); // just if you want to restart only once
    }
    else
    {
        label1.Content = "Before restart";
        stateFile.Write(true); // is restarted
        stateFile.Write(label1.Content); // if you want to restore that as well
        DoSomeMagicAutoStartOperation(); // TODO: Autostart folder or Registry key
        System.Diagnostics.Process.Start("ShutDown", "-r"); //restart
    }
}

答案 2 :(得分:-1)

您有两种选择:将应用程序添加到启动文件夹或将相应的密钥添加到Windows注册表中的运行密钥。

http://msdn.microsoft.com/en-us/library/aa376977(v=vs.85).aspx