I was wondering guys how can I close two Forms From with its Form_Closing Eventhandler.
Example:
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 CAlled LoginForm;
LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
var f = (MainForm)Application.OpenForms["MainForm"];
if(f!=null)
{
if(f==DialogResult.Yes)
Application.Exit();
}
}
My Problem is How Do I call e.cancel function in the MainForm so that I could Override the FormClosing e.cancel=false and Close the Application with Application.Exit(); From LoginForm
LoginForm is a Modal Dialog and its parent is MainForm.
After I have read your comment I suggest using a different approach for your problem.
Use the DialogResult
property of the login form to indicate if the app should be terminated or not, Here is an example, this code should run on the MainForm.
Note: It is a basic example that probably will need some modification according to your project, for example checking if there is some long process that runs and the form should be delayed and invoked after the process finished...
please read comments inside the example:
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();
}
}));
}
}
}