处理 WPF 退出事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7717222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:07:33  来源:igfitidea点击:

Handle a WPF Exit Event

wpfeventsclient-serverexit

提问by sohum

I was wondering if there was a way to handle a WPF Application Exit event such that the exit was cancelled. The use case is that I have a client-server situation where the server is a WPF app. I want the WPF app to notify the client when it is shutting down, but cancel the shutdown process. The client should receive the shutdown notification, do its own required cleanup and then ask the WPF app to shutdown via a request.

我想知道是否有办法处理 WPF 应用程序退出事件,以便取消退出。用例是我有一个客户端 - 服务器情况,其中服务器是 WPF 应用程序。我希望 WPF 应用程序在关闭时通知客户端,但取消关闭过程。客户端应收到关闭通知,执行自己所需的清理,然后通过请求要求 WPF 应用程序关闭。

Is this possible?

这可能吗?

回答by Rohit Vats

You can hook the event Closing on your main window like this -

您可以像这样在主窗口上挂钩事件 Closing -

<Window Closing="Window_Closing">

And in your event set the e.Cancel to true to stop the window from closing. In your case you can maintain some field which will be set once you get notification from client that he's done with cleanUp and its safe now to close the window. Simply set that value to e.Cancel

并在您的事件中将 e.Cancel 设置为 true 以阻止窗口关闭。在您的情况下,您可以维护一些字段,一旦您收到客户的通知,他已经完成了清理工作,并且现在可以安全地关闭窗口,该字段将被设置。只需将该值设置为 e.Cancel

private void Window_Closing(object sender, CancelEventArgs e)
{
   e.Cancel = true;
}

回答by CAD bloke

If you want stop the operating system being shut down, or at least clean up before it does, you need to handle the Application.SessionEnding.

如果您想停止关闭操作系统,或者至少在它关闭之前进行清理,您需要处理Application.SessionEnding

Related: Handling System Shutdown in WPF

相关:在 WPF 中处理系统关闭