2014-01-10 95 views
0

我写了下面一个简单的C#WPF代码,恢复系统重新启动后C#应用程序

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"; 

    } 

}

现在的问题是,我想以后重启和和显示消息作为自动恢复我的应用程序“重启后”。请帮助我如何实现这一目标?

+1

有你把你的应用程序到'AutoStart'文件夹或'Run'注册表项或任何类似? –

+2

_“我想重新启动后自动恢复我的应用程序” _ - 解释。如果您例如建立POS终端,则可能需要查看自助服务终端模式。无论如何,您不能只是在任意点恢复应用程序,您必须将状态存储在关机状态,并在重新启动后进行恢复。 – CodeCaster

回答

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服务。

+0

谢谢您的建议居停。我试图将应用程序的状态放在一些文本或XML文件中。我可否知道如何在启动时启动我的可执行文件以重新启动我的应用程序? – Anita

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 
    } 
} 
相关问题