Use the OnLayoutExit script trigger combined with get(windowname).
I ran a test and that worked fine for me.
The window name Main Menu suggests that you are maybe looking for a solution that people close the main menu window duiring their job. You could also use OnWindowClose, check for a certain condition indicating the window should not be closed and use Exit Script[false] to avoid the window closing.
What is the purpose, and why do you think it is not workinig?
If the window is last window of the file, global variable will vanish after closed.