trying to prevent user from exiting the application sometimes
-
There are times in my application that I want to prevent the user from exiting the application window with the exit button (the X button in the upper right hand corner of most window applications). I want in some circumstances to print out a message box and to let the user know that the application is in a state that cannot exit the application and to keep it running. The following code catches that application exiting from clicking on the exit button, and prints out the message box. But how can I stop the application from continuing with the exit ? Actually, by the time the message box is printed, the application window is already closed. I am fairly new at C #, any help is appreciated. static void Main(string [] args) { Application.ApplicationExit += new EventHandler(ApplicationExitEventHandler); Application.Run(new CsMain()); } static void ApplicationExitEventHandler(Object sender, System.EventArgs e) { if (state != CLOSED_STATE) { MessageBox.Show("Error ! \n\nThe line is still open. You must close the \nline before terminating the application", "CsTdrv", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
-
There are times in my application that I want to prevent the user from exiting the application window with the exit button (the X button in the upper right hand corner of most window applications). I want in some circumstances to print out a message box and to let the user know that the application is in a state that cannot exit the application and to keep it running. The following code catches that application exiting from clicking on the exit button, and prints out the message box. But how can I stop the application from continuing with the exit ? Actually, by the time the message box is printed, the application window is already closed. I am fairly new at C #, any help is appreciated. static void Main(string [] args) { Application.ApplicationExit += new EventHandler(ApplicationExitEventHandler); Application.Run(new CsMain()); } static void ApplicationExitEventHandler(Object sender, System.EventArgs e) { if (state != CLOSED_STATE) { MessageBox.Show("Error ! \n\nThe line is still open. You must close the \nline before terminating the application", "CsTdrv", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
Hi, Here I am assuming you are inheriting from the System.Windows.Forms.Form class. In the class add an EventHandler to the Closing Event e.g. Form.Closing += new CancelEventHandler(MyClose); Then create the code in here, you can cancel the event using the CancelEventArgs e.g. MyClose(object sender, CancelEventArgs) { ....... if(shouldNotClose) e.Cancel = true; } Hope this helps, Andy