Notification when connecting or disconnecting a display

I am working on an OS X application that displays custom windows in all available spaces of all connected displays. I can get an array of available display objects by calling [NSScreen screens].

What I'm currently missing is a way to tell if the user is connecting to the display or the screen is disconnecting from their system.

I was looking for Cocoa documentation for notifications that relate to a similar scenario without much luck, and I refuse to believe that there is not some kind of system notification that is sent when the number of displays connected to the system changes.

Any suggestions for resolving this issue?

+8
objective-c cocoa
source share
2 answers

There are several ways to achieve this:
You can implement applicationDidChangeScreenParameters: in your application deletion (this method is part of NSApplicationDelegateProtocol ).
Another way is to listen for the NSApplicationDidChangeScreenParametersNotification sent by the default notification center [NSNotificationCenter defaultCenter] .

Whenever you call the delegate method or get a notification, you can [NSScreen screens] over [NSScreen screens] and see if the display is connected or removed (you need to save the display list, which you can check when the program starts).

The approach without Cocoa will be through graphic display services:
You must implement the reconfiguration function and register it with CGDisplayRegisterReconfigurationCallback(CGDisplayReconfigurationCallBack cb, void* obj);

In your reconfiguration function, you can query the status of the affected display. For example:.

 void DisplayReconfigurationCallBack(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void* userInfo) { if(display == someDisplayYouAreInterestedIn) { if(flags & kCGDisplaySetModeFlag) { ... } if(flags & kCGDisplayRemoveFlag) { ... } if(flags & kCGDisplayDisabledFlag) { ... } } if(flags & kCGDisplaySetModeFlag || flags & kCGDisplayDisabledFlag || flags & kCGDisplayRemoveFlag) { ... } } 
+8
source share

in swift 3.0:

 let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(screenDidChange), name: NSNotification.Name.NSApplicationDidChangeScreenParameters, object: nil) 

NC:

 final func screenDidChange(notification: NSNotification){ let userInfo = notification.userInfo print(userInfo) } 
+3
source share

All Articles