Monday, October 31, 2005

Exiting or Closing a .NETCF application

For the better part of today I was trying to get the Form.Close() event of my applications' main form to get fired. But no matter what it seemed to not to get fired. And in the process of trying to figure out why it was not so, I found out a thing or two as well.

1. You should not use the Application.Exit() method to close the application. This makes the app to terminate the execution and return control to the system. ow you may say, that it is what you needed to do. But the bad part is this will not trigger the Close() or Closing() methods and hence the clean-up code is not performed. Also, if you have manually put any procs to execute in either of these events then they will not get executed.

So I changed from Application.Exit() this.Close(). But, still my Closing() event was not getting fired. So I delved further and discovered this. In .NETCF apps, the MinimizeBox property of the form is set to True by default. This is done to enhance the app performances. So this way, when the user clicks on the X button on the Top, the form is minimized. And hence, is the form is called again, it is being called from the memory; improving application performance. This is good in mos cases where you want the application to remain in the memory once it is loaded. But in cases where you want the application to quit, when closed, this is not good behavior. So what you have to do is to set the MinimizeBox property to False. Then the X on top righthand corner of the form will change into a OK. And clicking OK will actually quit the application.

Here is my code sample asking the user to confirm exiting application etc.

if (MessageBox.Show("Do you want to Exit the application?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
//Do whatever needs to be done.
this.Close();
}
else
e.Cancel = true; //This prevents the form from being closed.


Well, hope this helps someone out there.

1 comment:

Anonymous said...

Yes, you know, except you should design your application so that it's not closed, as per the platform rules, unless you have some veeeeeeery important reason.
Using "OK" to close the window does not make sense to the user unless they're, well, OK'ing something. Are they?