Make frames closable with the Escape key

From Warcraft Wiki
Jump to navigation Jump to search

To make a frame close when the user presses the ESC (Escape) key, add its name to the UISpecialFrames table:

tinsert(UISpecialFrames, frame:GetName())

Note that in order for this to work, your frame must have a name and be registered in the global variable list.

Example

The following XML snippet creates a frame that is closable by pressing Escape, and plays the sounds played when you open/close FrameXML panels (e.g. character frame).

<Frame name="ExampleFrame" parent="UIParent">
  <Size x="640" y="512" />
  <Anchors>
    <Anchor point="CENTER" />
  </Anchors>
  <Scripts>
    <OnLoad>
      tinsert(UISpecialFrames, self:GetName());
    </OnLoad>
    <OnShow>
      PlaySound(SOUNDKIT.IG_CHARACTER_INFO_OPEN);
    </OnShow>
    <OnHide>
      PlaySound(SOUNDKIT.IG_CHARACTER_INFO_CLOSE);
    </OnHide>
  </Scripts>
</Frame>

Example

The following lua snippet creates a frame that is closable by pressing Escape.

frame = CreateFrame("Frame", "MyFrame", UIParent, "BasicFrameTemplateWithInset");
_G["MyFrame"] = frame -- adds the frame via the name "MyFrame" to the global variables
tinsert(UISpecialFrames, frame:GetName()) -- instead frame:GetName() one could just use "MyFrame"

EditBoxes and OnEscapePressed

EditBox widgets that have focus will handle the Escape key being pressed by firing their own OnEscapePressed widget handler, preventing your frame from being closed while an edit box has focus. You may set your own OnEscapePressed handler on your edit boxes to hide a frame if necessary:

editBox:SetScript("OnEscapePressed", function(self)
 self:GetParent():Hide()
end)