2
votes

I want to create a borderless window floating above the main window. The main window should be the key window (I want it to handle the keyboard and mouse events). Also, the floating window should close as the user clicks outside of it. Basically, I'm creating a very custom context menu, just like NSMenu. It should behave likewise.

So I created my window this way:

NSWindow *menuWindow = [NSWindow windowWithContentViewController:menuViewController];

menuWindow.styleMask = NSBorderlessWindowMask;
menuWindow.level = NSFloatingWindowLevel;

[menuWindow makeKeyAndOrderFront:self];

That works perfectly, but how do I handle clicks outside to close it? The window doesn't invoke delegate's windowDidResignKey, because it's not a key window. If it does overload canBecomeKeyWindow (so that it returns YES), then the floating window grabs the user input, which is not what I want.

So, is there any way to automatically close a borderless window? Can NSPanel help? I tried using it, but with no success (the becomesKeyOnlyIfNeeded selector doesn't do what I need).

2

2 Answers

5
votes

To detect clicks outside the window but within your app, you could install an event monitor using +[NSEvent addLocalMonitorForEventsMatchingMask:handler:]. If you also want to close the window when the user clicks in a different app, you could observe the NSApplicationDidResignActiveNotification notification.

-1
votes

NSWindow has a property hidesOnDeactivate that should do this for you.

From the Apple Docs:

The value of this property is true if the window is removed from the screen when its application is deactivated; false if it remains onscreen. The default value for NSWindow is false; the default value for NSPanel is true.