我们可以知道一个窗口是否已被用户或 WPF 上的代码关闭? [英] Can we know if a window has been closed by the user or code on WPF?

查看:31
本文介绍了我们可以知道一个窗口是否已被用户或 WPF 上的代码关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个窗口控件显示在我的应用程序上.有时,窗口由用户关闭(单击X"按钮),有时由代码自动关闭.

I have a window control that I show on my app. Sometimes, the window is closed by the user (clicking on the 'X' button) and sometimes automatically by code.

我正在收听 Closed 事件(也尝试使用 Closing),并想知道我是哪种情况(用户或代码).这可能吗?

I'm listening to the Closed event (also tried with Closing) and would like to know in which case I am (user or code). Is this possible?

(我知道 this 问题,但它确实没有令人满意的答案)

(I am aware of this question but it really doesn't have a satisfactory answer)

我正在寻找一个简单的解决方案,或者某种了解事件起源的方法.我知道我可以按照 Sandeep Bansal 的建议自己实现这个功能.

I'm looking for a simple solution, or some way of knowing where the event originated. I know I can implement this functionality myself as Sandeep Bansal suggested.

推荐答案

选项 1:定义一个新类型

Option 1: Define a new type

 public class CodeClosingEventArgs : EventArgs
 { 
  // Fill any custom data you want
 }

然后在您的代码中显式调用 OnClosed(new CodeClosingEventArgs()); 并检查事件类型,如果它是正常"事件参数,则单击X"是用户.

And then call OnClosed(new CodeClosingEventArgs()); explicit in your code and check for the Event Type, if its a "normal" event arg, its the user by clicking the 'X'.

选项 2:

使用关闭表单的自定义方法.

use a custom method which closes your form.

 public void MyClosingFormMethod()
 {
    base.OnClosed(null); 
 }

这篇关于我们可以知道一个窗口是否已被用户或 WPF 上的代码关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆