Santiago Santiago - 3 months ago 8
C# Question

How to avoid an exit confirmation?

what I want to do is simple but I do not know how to do it. I'm doing a basic window login, and I wrote a code to ask for confirmation before exit, like this: (I have the names in spanish, the "Contador" is the counter if you do not understand)

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogo = MessageBox.Show("¿Desea cerrar la aplicación?",
"Aviso!", MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (dialogo == DialogResult.No)
{
e.Cancel = true;
}
}


What I've done after that, is a counter that if I entry the incorrect information three times, the application is going to close, here's the code:

private int Contador;
private void Form1_Load(object sender, EventArgs e)
{
Contador = 0;
aceptar.Enabled = false;
usuario.MaxLength = 40;
contraseña.MaxLength = 10;
}

private void aceptar_MouseClick(object sender, MouseEventArgs e)
{
if(Contador == 2)
{
DialogoCerrar();
Close();
}
if (usuario.Text == ("Demo") && (contraseña.Text == ("ABC123")))
{
Contador = 0;
DialogResult dialogo = MessageBox.Show(
"Ingreso exitoso!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
DialogResult dialogo = MessageBox.Show(
"Datos incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
Contador++;
}
}


So, this works, but when after three times I put the incorrect information, before to close the program ask me if I want to do it (I know that is for the Form1_FormClosing), and I want that the program doesn't ask it in that situation.

Answer

You just need to set a flag:

private bool _noConfirmExit;

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (_noConfirmExit)
    {
        return;
    }

    DialogResult dialogo = MessageBox.Show("¿Desea cerrar la aplicación?", "Aviso!", MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
    if (dialogo == DialogResult.No)
    {
        e.Cancel = true;
    }
}

private void aceptar_MouseClick(object sender, MouseEventArgs e)
{
    if(Contador == 2)
    {
        _noConfirmExit = true;
        DialogoCerrar();
        Close();
    } 

    if (usuario.Text == ("Demo") && (contraseña.Text == ("ABC123")))
    {
        Contador = 0;
        DialogResult dialogo = MessageBox.Show("Ingreso exitoso!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    else
    {
        DialogResult dialogo = MessageBox.Show("Datos incorrectos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        Contador++;
    }
}

That way, your FormClosing event handler can tell the difference between closing for other reasons and closing because the counter reached its limit.