Escape button multipurpose

I want to do something we see in so many games, if any kind of window interface is opened (inventory, character sheet, etc.), pressing the escape button should close them, but if not, then it should open the game menu and pause the game.

At first i thought i could use the consume input and input priority easily by consuming the escape input in any new widget added to the viewport, but then i realized that i can not use any input action event in a widget.

So i would like to know what is the easiest way to do this feature, do i have to do something like keeping track of any added widget in an array and if the array length is not equal to 0, then close them or is there a better way to do it ?

Can probably use the function for OnKeyDown (you have to override it). May only work if the widget has explicit focus though. Manually tracking them with an array is more likely to work IMO.