Auto closing dialog boxes.

Auto closing dialog boxes.
I have a requirement to close any existing Dialog boxes on receipt of a
hardware trigger, to ensure that one of two TWindows are visible. It
appears that two situations can hide my data, (1) Dialog boxes and (2) a
dropped down menu (or two). On this trigger I've tried sending the
application cmCancel - this closes the dialog boxes but I can't tell when
the TWindow is on top. It has no effect on the menu bar. Sending kbEsc
key codes to the application is messy and may have side effects.
What is the proper technique I should be using?