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 macOS swift August 6, 2020 How to open an app's window on top of all others in Swift?

You can open your app’s window on top of all other open application windows with the below code:

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.