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

Hello,
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.
Chris

struct MyView: View {
    @Environment(\.scenePhase) var scenePhase
    var body: some View {
        Text("Testing")
            .padding()
            .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:

https://developer.apple.com/documentation/appkit/nswindow/1419735-iskeywindow

Peter thank you. This was the key. I had some trouble understanding how to implement it but found this site which was very helpful. https://lostmoa.com/blog/ReadingTheCurrentWindowInANewSwiftUILifecycleApp/. 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.

From this article it looks like we can use the controlActiveState environment for mac - Detect focused window on macOS

@Environment(\.controlActiveState) var controlActiveState

controlActiveState == .key // window became active
controlActiveState == .inactive // window became inactive