Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing event triggered on both UserClosing and this.close

Tags:

c#

.net

winforms

I have a form on which there is a LogOutEvent and a form closing event. Here is the code,

private void btnLogOut_Click(object sender, EventArgs e)
{
       DialogResult yesNo = MessageBox.Show(this, "Are you sure you want to Log Off?", "Log Off", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

        if (yesNo == DialogResult.Yes)
        {
            new LoginForm();
            this.Close();
            string tst2 = Logout(AgentId, AgentPwd, ExtensionId);
            if (tst2 == "TCF000")
                MessageBox.Show(" Logout Success");
            else
                MessageBox.Show("Logout Failed");
        }
}

And a Form Closing Event

private void MainGUI_FormClosing(Object sender, FormClosingEventArgs e)
{
        if (e.CloseReason == CloseReason.UserClosing)
        {
            DialogResult yesNo = MessageBox.Show(this, "Are you sure you want to Log Off?", "Log Off", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

            if (yesNo == DialogResult.Yes)
            { 
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
         }
}

My Problem is when i click on the LogOut button its calling the form closing event. Can anybody advice a better code for this?

When i click on close 'X' it should close the application and when i click on LogOut it should close the current window and go to the login form.

like image 570
Chandra Eskay Avatar asked Apr 07 '11 06:04

Chandra Eskay


2 Answers

I'm sure that there is a better solution, but this does work:

private bool loggingOut;

private void Form1_DoubleClick(object sender, EventArgs e)
{
    this.loggingOut = true;
    this.Close();
    // This is optional as we are closing the form anyway
    this.loggingOut = false;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing && !loggingOut)
    {
        // Handle form closing here
    }
}

This allows your form closing event handler to identify if another method is invoking the form close, and skip the normal handling if it is.

Alternatively you could just Hide the form instead, and re-use the same form instance the next time the user logs in.

like image 168
Justin Avatar answered Sep 30 '22 06:09

Justin


well... yes! the form is closing; why wouldn't it fire the event?

If the CloseReason isn't helping, then just throw a bool field onto the form that you set to true when you click logout; and check that field in the closing event.

like image 26
Marc Gravell Avatar answered Sep 30 '22 08:09

Marc Gravell