Error 365, “Unable to unload within this context”, means the Unload statement itself was legal but its location was not. Some moments in a form's life cannot tolerate the form being destroyed: inside particular events, while the host is in the middle of its own processing, or from contexts such as a control's paint cycle in classic VB. The object could be unloaded a moment later from a different place; the context, not the object, is the problem. It is a timing bug in the code.
' In the event that cannot unload:
wantsClose = True
tmrClose.Enabled = True ' one-shot timer, short interval
' In the timer, now in a safe context:
Private Sub tmrClose_Timer()
tmrClose.Enabled = False
Unload Me
End Sub
Me.Hide now and Unload at the safe point gives the user the right experience without breaking the context rule.If the unload sits in an ordinary button handler and error 365 still fires, the handler may be running inside a host-controlled context: a modeless form driven by an external caller, or code running during the host's own event processing. Log the call stack at the failure; the frames above the handler reveal who owns the context.
Why would Unload ever be forbidden? Because destroying a form while the system is inside that form's own event processing leaves the processor with no object to return to. The runtime forbids the unload at those moments rather than crashing.
Is the timer deferral a hack? It is the documented, standard pattern for this situation: it moves the unload to the next safe message-processing point. The alternative designs (flags checked by the caller, Hide plus deferred unload) achieve the same move.