I'm using Environment.Exit() in the OnClosing event to make sure no threads are zombied when I close my app, and it's fine, that works. The problem is that every now and then closing the app throws an exception that I can't control.
Unhandled exception of type 'System.ComponentModel.Win32Exception' in System.Windows.Forms.dll
Failed to create window handle.
I have tried to use Try/catch but it doesn't help, the exception keeps throwing.
Does anyone know how I can properly handle this situation?
This is the code that is giving me the problem:
public void OnClosing(FormClosingEventArgs e)
{
if (MessageBox.Show("Desea cerrar el programa?", "Advertencia",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
return;//no salir
}
try
{
Environment.Exit(Environment.ExitCode);//--> aquí se produce la excepción (Error al crear identificador de)
}
catch (System.ComponentModel.Win32Exception ex)
{
string message = "AppClose::OnClosing()-> " + ex.Message + " Error code: " + ex.ErrorCode;
MessageBox.Show(message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Thank you very much!!
It is normal that you do not catch that exception, after all, the code on which you do
try
it does not throw it. If we consult the documentationEnvironment.Exit
we see the following:And it is logical. Why would it throw an exception with an error of creating windows a function that closes the system?
Is there another part of your code that creates windows that is not inside the block
try
? My main suspect is theMessageBox
, which is a window after all and is not in the blocktry
, try doing this: