Krowi
Krowi

Reputation: 1615

Calling Form.Close in Form.Closing

I've been given the task to clean up an application that my company is using. The previous developer is not working at the company anymore and I have a question.

In a certain form there is a Form.Closing method. In this method some custom code is written. The last line in this method is the Close(); call. When looking for the source it goes back to System.Windows.Forms.Form.Close.

This code sample is visible below:

private void Form1_Closing(object sender, CancelEventArgs e)
{

    // Some custom code here.

    Close();
}

When debugging, when the code arrives at Close(); it jumps back to the Form1_Closing method. This would lead to an endless recursive call ending in a stack overflow. Now, on Windows 7 I sometimes get a stackoverflow error. On Windows 10 this does not happen. Does anyone know why my old colleague has put the Close call in the Closing method?

If more information is required I will try to provide it. For now I just put the Close call in comments and everything appears to be working as before, now also without occasional bugs (stackoverflows) on Windows 7.

Upvotes: 1

Views: 1682

Answers (2)

Xar Hang
Xar Hang

Reputation: 21

maybe the programmer doesn't want to close this form. just need to looping the statement in side form_closing. if want to close this form just remove or comment close() then it will working. if you want to return the resource to computer you need to put Dispose() at the end of this method.

Upvotes: 0

rokkerboci
rokkerboci

Reputation: 1167

The closing event is triggered when the form is about to close. You don't have to call the close method, as that is what invoked the event in the first place.

If you want the form to close, simply do nothing, since it will close when exiting the on closing callback.

If you want to prevent it from closing, you can write e.Cancel = True, which will prevent the form from closing.

Your college may have called the close method, because there were an overloaded version of it, but at some point got removed. Or maybe he/she wanted to close another form as well. The important thing is, that you don't need to call that method in this case.

Upvotes: 4

Related Questions