[英]Resuming a C# application after system restart
我編寫了一個簡單的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";
}
}
現在的問題是我想在重啟后自動恢復我的應用程序,並顯示消息為“重啟后”。 請幫我實現這個目標...
解決此問題的方法是在硬盤或某些永久內存(如自定義事務文件)中保持狀態。
例如
應用程序將有不同的階段。 處理成文件后,我將進入每個階段。 一台機器停止,然后如果應用程序自動啟動,它將從該文件讀取該階段,然后從該階段進行處理。
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服務。
這是一個概念(偽代碼):
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
}
}
您有兩種選擇:將應用程序添加到“啟動文件夾”或將適當的密鑰添加到Windows注冊表中的運行密鑰。
http://msdn.microsoft.com/en-us/library/aa376977(v=vs.85).aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.