Loading...

How to detect Escape key pressed in macOS apps?

question macOS swift
Ram Patra Published on March 14, 2021

Like Delete key, detection of Escape key press is also slightly different than detecting general key presses.

if Int(event.keyCode) == kVK_Escape {
  print("Escape key pressed!")
}

Below is the full sample code:

NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
  if self.keyDown(with: $0) {
    return nil // needed to get rid of purr sound
  } else {
    return $0
  }
}

private func keyDown(with event: NSEvent) -> Bool {
  if Int(event.keyCode) == kVK_Escape {
    print("Escape key pressed!")
    return true
  } else {
    return false
  }
}
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on March 14, 2021
Image placeholder

Keep reading

If this article was helpful, others might be too

question macOS swift August 14, 2020 How to detect Delete key press in Swift?

Delete key press detection is slightly different than other keys. It uses NSDeleteCharacter like below:

question macOS swift March 14, 2021 How to ignore mouse events in a view or window in macOS?

You can ignore mouse events in a window/view by adding just a single line of code.

question presentify macOS August 6, 2020 How to annotate or draw in JioMeet?

Reliance Jio has done a commendable job releasing a video conferencing app in a short time frame, however, it received criticisms that it copied pixel by pixel from Zoom. I actually agree with some of the criticisms but that’s for another blog post.