How to delay window closing in WPF
I try to delay close a window in my App.xaml.ca :
Window splash = new Window();
splash.Show();
Timer timer = new Timer(callback, null, 2000, Timeout.Infinite);
private void callback(object stateInfo)
{
splash.Close();
}
It w开发者_运维知识库orks fine, but the whole App is shutdowning. What am doing wrong here ?
Be sure to check that you timer callback is coming back on the main dispatcher thread. If not then you will likely be getting an exception when you try to close your window from a different thread.
Use splash.Dispatcher.CheckAccess()
to make sure you are on the right thread and if not then use splash.Dispatcher.BeginInvoke((Action) () => splash.Close()
to dispatch the call onto the main thread.
Check out this page for more
Here is my solution to this exact same problem:
private async void CloseWindow()
{
await ClosingTasks();
}
private async Task ClosingTasks()
{
await Task.Delay(2000);
this.Close();
}
Where you simply call CloseWindow() when you want to close the current window after the given delay of 2000 mS.
There are different shutdown modes, if that window is closed and it is the last then the application will shut down by default. So you can either see to it that there is still some window around or you can change the shutdown behaviour by setting the ShutdownMode
to something that suits your needs.
e.g.
Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
精彩评论