swiftmacoscocoanswindow

How to show a window without stealing focus on macOS?


I was wondering how could spotlight floating with focus, and another window still has focus!

enter image description here

I could easy make a window floating over all other window with window?.level = Int(CGWindowLevelForKey(.maximumWindow)),but I cannot let two windows both has focus, help!

Is there any function like ShowWithoutActivating in Cocoa?


Solution

  • I've been playing around with this a bit, and I seem to be able to produce this effect when the frontmost window is not from the same process as the frontmost application, which is what I suspect Spotlight is probably doing. I can achieve this like so:

    1. Set LSUIElement to YES in my app's Info.plist.

    2. In Interface Builder, set the window's class to NSPanel, check "Non Activating" in the Attributes Inspector, and set "isFloatingPanel" to YES in the User Defined Runtime Attributes under the Identity Inspector.

    3. During some time that some other application is in front (I just used a 5-second delay to give myself time to pop some other app to the front and select a text field), call makeKeyAndOrderFront() followed by orderFrontRegardless() on the window.

    When I do this, I get the following (note the focus ring still drawn on Xcode's "Module" field):

    enter image description here