我想知道我怎么能关闭两个窗体从它的Form_Closing eventandler
的例子:
MainForm;
MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
var d = (MessageBox.Show("Exit Program","Confirm",MessageBoxButton.YesNo,MessageBoxIcon.Question);
if(d== DialogResult.Yes)
{
e.cancel=false;
}
else
{
e.cancel=true;
}
}
In Another Form CAlledLoginForm;
LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
var f = (MainForm)Application.OpenForms["MainForm"];
if(f!=null)
{
if(f==DialogResult.Yes)
Application.Exit();
}
}
我的问题是如何在MainForm中调用e.cancel函数,以便我可以覆盖FormClosing e.cancel=false并使用Application. exit()关闭应用程序;从LoginForm
LoginForm是一个模态对话框,它的父类是MainForm。
在我读了你的评论之后,我建议使用不同的方法来解决你的问题。
使用登录表单的DialogResult
属性来指示应用程序是否应该被终止,下面是一个例子,这段代码应该在MainForm上运行。
注意:这是一个基本的例子,可能需要根据您的项目进行一些修改,例如检查是否有一些长过程正在运行,表单应该延迟并在过程完成后调用…
请阅读示例中的注释:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Start the measuring time for reauthentication
StartReAuthTimer();
}
// The session allowed time
private const int AllowedSessionSecconds = 30*60;
// Timer to check if user passed the allowed time
private System.Timers.Timer ReAuthTimer;
// holds the beginning of session time
DateTime LastSessionBeginTime;
// indicates if the login form is open
private bool IsLoginFormShown = false;
private void StartReAuthTimer()
{
if (ReAuthTimer == null)
{
ReAuthTimer = new System.Timers.Timer();
}
IsLoginFormShown = false;
ReAuthTimer.Interval = 10000;
LastSessionBeginTime = DateTime.Now;
ReAuthTimer.Elapsed += ReAuthTimer_Elapsed;
ReAuthTimer.Start();
}
private void CancelTimer()
{
ReAuthTimer.Elapsed -= ReAuthTimer_Elapsed;
ReAuthTimer.Dispose();
ReAuthTimer = null;
}
private void ReAuthTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (DateTime.Now >= LastSessionBeginTime.AddSeconds(AllowedSessionSecconds) && IsLoginFormShown == false)
{
// ReAuthenticate
IsLoginFormShown = true;
CancelTimer();
LoginForm login = new LoginForm();
// Show the login form, note: because we are running on the main thread we will use Invoke()
this.Invoke(new Action(() =>
{
DialogResult result = login.ShowDialog();
if (result == DialogResult.Cancel)
{
// The user closed the form
Application.Exit();
}
else
{
// Authenticated succesfuly - start timer again
StartReAuthTimer();
}
}));
}
}
}