In macOS how do you detect if my program window is selected or no longer selected on the screen?

I am trying to detect when my running swift program window is selected and not selected. The not selected case example would be Safari is now active and at the forefront but my swift program window is still on the screen just gray. I have looked at focus but it appears to apply to which element in a scene has focus, such as a text box. I also looked at active/inactive/background scene phases but in the example above (ie bringing Safari to the forefront) the scene phase does not appear to change in my test program. Any assistance in pointing me in the right direction will be appreciated.
Below is the code I used to test active/inactive/background.

struct MyView: View {
    @Environment(\.scenePhase) var scenePhase
    var body: some View {
            .frame(width: 600, height: 400, alignment: .center)
            .onChange(of: scenePhase, perform: { phase in
                switch phase {
                case .active: print("Active")
                case .background: print("Background")
                case .inactive: print("Inactive")
                default: print("Who Knows")

Use the isKeyWindow property:

Peter thank you. This was the key. I had some trouble understanding how to implement it but found this site which was very helpful. Now when I select another window the isKeyWindow variable (a boolean) changes to false and back to true when I select the program window again. Perfect.

Terms of Service

Privacy Policy

Cookie Policy