Yuki Kutsuya
Yuki Kutsuya

Reputation: 4088

C# formclosing event and loops

If I have to declare a little bit more please tell me, it's a little bit late here.

I have a little problem, this code keeps looping :(...

I have this

if (MessageBox.Show("Are you sure you want to quit?", "Confirm Quit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
    Stop();
    _exited = true;

    foreach (Process x in Process.GetProcesses())
    {
        while (x.Id == _processID)
        {
            Application.Exit();
            e.Cancel = true;
            return;
        }
    }
}

Upvotes: 1

Views: 546

Answers (1)

dknaack
dknaack

Reputation: 60486

Description

It keeps looping because you call Application.Exit() inside this method. I dont know what you trying to do but i think you want to ask the user if he really wants close the app. If your set e.Cancel = trueit means you cancel the event, so in your case you cancel to close the app.

So if your ask "sure you want to quit" and user choose "No" you should set e.Cancel = true, if not do nothing because the default value of e.Cancel is false.

Sample

// create a list of process
private List<Process> processes = new List<Process>();

// if you start a process
Process myProcess = //;
processes.Add(myProcess);

// on closing
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    var isAProcessRunning = processes.Where(p => p.HasExited == false);

    if (isAProcessRunning.Any()) 
    {
      // some process is already running, ask the user 

        if (MessageBox.Show("Are you sure you want to quit?", "Confirm Quit", MessageBoxButtons.YesNo) ==
        DialogResult.No)
        {
            e.Cancel = true;
        }
     }
  }

More Information

Upvotes: 1

Related Questions