Dominik Palo Dominik Palo - 1 year ago 163
Swift Question

Can't handle key events from fullscreen NSWindow

In my OS X app I need to close a fullscreen window with the Esc key. So I set my instance of

as a first responder for my window (dynamically created from code in controller), overrode the
function with my custom implementation to close the window. But unfortunately, when window has set level to
functions are not called (of course before I press Esc I click to the fullscreen window so window should has focus)

I'm creating the window with:

self.window = NSWindow(
contentRect: screen.frame,
styleMask: NSBorderlessWindowMask,
backing: NSBackingStoreType.Buffered,
defer: false,
screen: screen

if let w = window {
w.level = Int(CGShieldingWindowLevel())
w.backgroundColor = NSColor.blackColor()

self.webView = WKWebView(frame: w.frame, configuration: config)
w.contentView = webView!

and handle keys with:

override func keyDown(theEvent: NSEvent) {
if (theEvent.keyCode == 53) {

Answer Source

See the docs for NSWindow.canBecomeKeyWindow. By default, a borderless window can't become key. You have to override that (and maybe canBecomeMainWindow) to return true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download