[英]How to execute code when Universal Windows Store App is closing?
I am developing an app for Windows 10 Store app, but I can't seem to find/learn on how to check if the user pressed the red close button (at the top right) or by pressing Alt + F4 . 我正在为Windows 10商店应用程序开发一个应用程序,但我似乎无法找到/学习如何检查用户是否按下红色关闭按钮(在右上角)或按Alt + F4 。 Basically what I want is something like this: 基本上我想要的是这样的:
private void app_Close(object sender, CloseEventArgs e)
{
//saves some data in the app :D
}
If you have a Universal app that doesn't have a MainWindow object you'll probably want to tap into the "Suspending" event: 如果你有一个没有MainWindow对象的通用应用程序,你可能想要进入“暂停”事件:
appObject.Suspending += (s, a) =>
{
SaveTheData(); // I really like my data and want it for later too
};
or 要么
public App()
{
/*
stuff
*/
Suspending += (s, a) =>
{
SaveTheData(); // I really like my data and want it for later too
};
}
Add a handler to your MainWindow "Closing" event to save your data. 在MainWindow“Closing”事件中添加处理程序以保存数据。 Once "Closing" has finished, "Close" should fire normally. “结束”完成后,“关闭”应该正常启动。
theMainWindowObject.Closing += (s,a) =>
{
SaveTheData(); // It's precious!
};
I have something similar to this in one of my smaller applications where in the constructor for MainWindow I put the above snippet substituting "theMainWindowObject" for "this" so that it references itself 我在一个较小的应用程序中有类似的东西,在MainWindow的构造函数中,我把上面的代码段替换为“theMainWindowObject”代替“this”,以便它引用自己
So I have: 所以我有:
public MainWindow()
{
// Note: "this." isn't necessary here but it helps me with mental accounting
this.Closing += (s, a) =>
{
Save();
};
}
If you're just saving one or two properties and don't have any crazy logic going on you can just drop it right in the handler: 如果您只是保存一个或两个属性并且没有任何疯狂的逻辑,那么您可以将它放在处理程序中:
public MainWindow()
{
Closing += (s, a) =>
{
Properties.Settings.Default.SettingsPopupX = mySettingsPopupObject.GetX();
Properties.Settings.Default.SettingsPopupY = mySettingsPopupObject.GetY();
Properties.Settings.Default.Save();
};
}
If you want to manage your Application Lifecycle have a look at this MSDN article: https://msdn.microsoft.com/en-us/library/windows/apps/mt243287.aspx In general you don't have a "close" event in Windows Apps. 如果您想管理您的应用程序生命周期,请查看此MSDN文章: https : //msdn.microsoft.com/en-us/library/windows/apps/mt243287.aspx一般情况下,您没有“关闭” Windows Apps中的事件。 Your App will be suspended when Windows or your user wants to close it. 当Windows或您的用户想要关闭它时,您的应用程序将被暂停。 Using the ApplicationExecutionState
(see more) enum you can find out who (windows or your user) closed the app. 使用ApplicationExecutionState
(查看更多)枚举,您可以找出谁(Windows或您的用户)关闭了应用程序。
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.