我正在显示表单,30秒后表单必须自动关闭。 为了关闭表单,我调用this.Close()来自Timers.Timer控件,它将在30秒后关闭表单。
private void DISPLAY_FormClosed(object sender, FormClosedEventArgs e)
{
//some stuff
timerClose.Stop();
}
但是如果用户希望通过单击X按钮关闭表单,那么我应该可以区分表单是由用户还是计时器关闭。 我确实有FormClosed事件在关闭时做一些事情,但在这里我需要知道表单是由用户还是计时器关闭。
{{1}}
我如何知道FormClosed事件中用户或计时器已关闭表单?
以下链接无法提供帮助
Can we know if a window has been closed by the user or code on WPF?
提前致谢。
答案 0 :(得分:2)
您只需要创建一个bool
(我称之为用户关闭),并在计时器关闭您的表单时相应地更改它。在这种情况下,如果计时器关闭它,它不再“被用户关闭”,所以我将其设置为false
。然后在你的结束活动中,检查一下布尔。
示例:强>
//As long as its not closed by the system, its closed by the user
private bool closedByUser = true;
private void timerClose_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate ()
{
//closed by system
closedByUser = false;
this.Close();
});
}
else
{
this.Close();
}
}
private void DISPLAY_FormClosed(object sender, FormClosedEventArgs e)
{
if(closedByUser)
timerClose.Stop();
//Closed by user
else
timerClose.Stop();
//Not closed by user
}