Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No keyboard capture without title bar

I am trying to build an animation using spriteKit and that could be controlled via keyboard (arrow keys to speed up, slow down, rewind the animation).

Also I need this application to have a completely transparent background, this I managed using :

scene?.backgroundColor = NSColor.clearColor()

as well as :

self.window.opaque = false

Up until now everything is working fine and I am able to control my animation. But as soon as I try to remove the title bar in Interface Builder by unchecking the box for my window on the right panel the keyboard capture stops working.

keyDown: is not called anymore and I get that 'dong' sound characteristic of when your mac tells you that keyboard input is not an option. Even though I still have the name of my app on the menu bar.

Is there any way to still be able to receive keyboard input when the title is off ?

like image 907
The Tom Avatar asked May 28 '15 06:05

The Tom


2 Answers

By default NSWindow instances return false from canBecomeKeyWindow if the window has no title bar. The following quote is from the relevant section in the NSWindow class reference.

Attempts to make the window the key window are abandoned if this method returns false. The NSWindow implementation returns true if the window has a title bar or a resize bar, or false otherwise.

So, to get the behaviour you're after you need to subclass NSWindow, and return true from canBecomeKeyWindow.

like image 173
Paul Patterson Avatar answered Oct 19 '22 06:10

Paul Patterson


As pointed out by Paul Pattersion (accepted answer) the trick was to subclass NSWindow in order to return true for canBecomeKeyWindow. For anyone wondering how to do that, here is the code:

import Cocoa

class CustomWindow: NSWindow {
    override var canBecomeKeyWindow: Bool {
        get { return true }
    }
}
like image 38
The Tom Avatar answered Oct 19 '22 07:10

The Tom