Skip to content

Instantly share code, notes, and snippets.

@HuakunShen
Created December 12, 2024 10:01
Show Gist options
  • Select an option

  • Save HuakunShen/0490921e1b0863ba2f34537afdb13ed9 to your computer and use it in GitHub Desktop.

Select an option

Save HuakunShen/0490921e1b0863ba2f34537afdb13ed9 to your computer and use it in GitHub Desktop.
Swift Monitor Active App Switching
import Cocoa
import Foundation
class AppSwitchMonitor {
let workspace = NSWorkspace.shared
var observers: [NSObjectProtocol] = []
func startMonitoring() {
// Monitor active application changes
let appObserver = workspace.notificationCenter.addObserver(
forName: NSWorkspace.didActivateApplicationNotification,
object: nil,
queue: .main
) { notification in
if let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication {
print("Switched to application: \(app.localizedName ?? "Unknown")")
print(app)
}
}
// Monitor active window changes
let windowObserver = NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWindow.didBecomeKeyNotification,
object: nil,
queue: .main
) { notification in
if let window = notification.object as? NSWindow {
print("Switched to window: \(window.title)")
}
}
observers.append(contentsOf: [appObserver, windowObserver])
}
func stopMonitoring() {
observers.forEach { observer in
workspace.notificationCenter.removeObserver(observer)
}
observers.removeAll()
}
}
func handleSIGINT(signal: Int32) {
print("Received SIGINT, stopping monitor...")
monitor.stopMonitoring()
exit(signal)
}
// Create and start the monitor
let monitor = AppSwitchMonitor()
monitor.startMonitoring()
// Set up signal handler for SIGINT
signal(SIGINT, handleSIGINT)
// Keep the program running
RunLoop.main.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment