Dominik Palo
Dominik Palo

Reputation: 3111

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 NSWindowController as a first responder for my window (dynamically created from code in controller), overrode the keyDown function with my custom implementation to close the window. But unfortunately, when window has set level to CGShieldingWindowLevel, keyDown and keyUp 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()
        w.makeKeyAndOrderFront(self)
        w.makeFirstResponder(self)

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

and handle keys with:

override func keyDown(theEvent: NSEvent) {
    if (theEvent.keyCode == 53) {
        self.window?.close()
    }
}

Upvotes: 2

Views: 620

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90541

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.

Upvotes: 5

Related Questions