Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error catching close in C#

Tags:

c#

I'm trying to catch the close of my form so that when a user exits, it saves "User has exited" to a text file, this is my code:

private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
   {

        if (String.IsNullOrEmpty(directory))
        {
            Close();
            e.Cancel = false;
        }
        else
        {
            string time = DateTime.Now.ToString("hh:mm");

            TextWriter msg = new StreamWriter(directory, true);

            msg.WriteLine(" (" + time + ") == " + uName + " Has Left The Chat == ");

            msg.Close();

            Close();
            e.Cancel = false;
        }
   }

My problem is, I get this error:

"Make sure you do not have an infinite loop or infinite recursion"

Any ideas on how to fix this?

like image 915
Connor Avatar asked Dec 11 '22 15:12

Connor


2 Answers

You cannot call the Close() method from form closing. Remove all the Close() calls and it will work.

private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (String.IsNullOrEmpty(directory))
    {
        e.Cancel = false;
    }
    else
    {
        string time = DateTime.Now.ToString("hh:mm");

        using(TextWriter msg = new StreamWriter(directory, true))
        { 
            msg.WriteLine(" (" + time + ") == " + uName + " Has Left The Chat == ");
            msg.Close();
        }
        e.Cancel = false;
    }
}
like image 178
Patrick D'Souza Avatar answered Dec 27 '22 16:12

Patrick D'Souza


You don't need to be calling the Close() method. Someone already called it, if the mainForm_FormClosing event was executed.

like image 45
Darin Dimitrov Avatar answered Dec 27 '22 16:12

Darin Dimitrov