Application.Run throws ArgumentException was unhandled
I have a condition where I need to close my application and so I call this.Dispose () when I set the certian flag.
At first I thought it was a function call issue after I call this.Dispose () and so I moved the code to be the last one, but I still get an "ArgumentException was unhandled" message. The parameter is not valid. "On Application.Run (newline myApp ().
What am I doing wrong? Did I miss something? Or maybe there is a better way to close the application?
source to share
Try using Application.Exit()
to exit the application.
When you use Application.Run(new MyForm());
, a message loop is created on the thread using the form object as the main form. It tries to deliver Win32 messages arriving at the application to their respective objects. However, when you call Dispose()
on the form object, you have not yet exited the message loop. When it tries to deliver the next message to your form object, it fails because it is already located and throws an exception. You have to either request the form to be closed (by calling Close
on the form), which will then ask the form to handle the event, and if it does, exit the message loop after that. Another way (more direct way) is to completely close the message loop on the thread by calling Application.Exit()
, which will close all associated forms.
source to share