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 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 macOS swift November 10, 2021 How to detect fn key press in Swift?

You can override the flagsChanged() method of NSViewController and have your code like below to detect fn key press and release in macOS:

question swift macOS October 29, 2023 How to make Color conform to RawRepresentable in SwiftUI 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.