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
  }
}
Ram Patra Published on March 14, 2021
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui macOS January 26, 2024 How to hide the title bar in a SwiftUI macOS app?

Let’s say you have a view named ContentView and your main App file looks like this:

question swift macOS October 29, 2023 How to make Color conform to RawRepresentable in Swift in macOS?

For various reasons you may want to convert the Color type to a String. And, below is a relatively cleaner way to do it.

May 28, 2020 Best Mac Apps for Working From Home

For me personally, it is a mixed feeling working from home. On one hand, I have the flexibility with when to work and when not to but on the other hand, it is sometimes hard for me to find that fine line between work and life. There are days when I keep working even after office hours without realizing that I have got my life wife too :)