0

When the user presses the close button in my form, I am executing a piece of code that stops a process (java.exe) via a messagebox. So if you press the "Yes" button the program scans through all the processes that are running and checks if the process is running. If the process is not running thehn kill the application.

The problem is that the message is popping up multiple times. This happens because he keeps activating the closing event, but I don't know how to code this the right way.

if (_isRunning)
{
    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;
            }
        }
    }
}

Any ideas?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Yuki Kutsuya
  • 3,968
  • 11
  • 46
  • 63
  • How's the user activating the close event multiple times? Isn't the dialog box modal? – Jeff Apr 27 '12 at 18:43

2 Answers2

0

How about disabling the Close button (or the whole form) after it is pressed? That way, the user is not presented with an apparently-enabled Close button that does nothing useful.

Generally it's a bad idea to block user input for such a long period... it might be worth putting up a progress bar if the operation takes more than perhaps 1 second to complete.

Also, your use of Application.Exit() looks fishy. What exactly are you trying to accomplish in the foreach block?

Also see How do I properly close a winforms application in C#?

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
0

Since you're in the message loop, you can just prevent multiple calls without the hassle of multithreading:

private bool _isClosing = false;

void Form_Closing(object sender, EventArgs e) {
    if (_isClosing) return;

    _isClosing = true;
   if (_isRunning) {
      // ....Clean up code....
   }
   _isClosing = false;
}
Mark Brackett
  • 84,552
  • 17
  • 108
  • 152
  • Personally I think it's a better user experience to disable the Close button and provide some sort of progress bar to the user (if the close event will take > 1 second). Otherwise, the user is left with an active Close button that does nothing. – Eric J. Apr 27 '12 at 18:45