Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatically switching the dock position when connecting or disconnecting another monitor
// compile command:
// xcrun clang -o dock_monitor dock_monitor.m -fobjc-arc -isysroot $(xcrun --show-sdk-path) -framework Foundation -framework AppKit -Wall -Wshadow -Wextra
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
void changeDockPosition(CGDirectDisplayID displayID, NSString *position)
{
// Retrieve the defaults dictionary and change the orientation key to
// the new position
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary<NSString *, id> *dockDefaults = [defaults persistentDomainForName:@"com.apple.dock"];
NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:dockDefaults];
[newDict setObject:position forKey:@"orientation"];
[defaults setPersistentDomain:newDict forName:@"com.apple.dock"];
// kill the dock, which will cause it to restart and use the new setting.
NSRunningApplication *dock = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.dock"][0];
[dock terminate];
// output the current position
NSString *dockParameterYouWant = [[defaults persistentDomainForName:@"com.apple.dock"] valueForKey:@"orientation"];
NSLog(@"%x added, dock is %@", displayID, dockParameterYouWant);
}
static void displayChanged(CGDirectDisplayID displayID, CGDisplayChangeSummaryFlags flags, void *userInfo) {
(void)userInfo;
@autoreleasepool
{
if (flags & kCGDisplayAddFlag) {
// display has been added
changeDockPosition(displayID, @"bottom");
}
else if (flags & kCGDisplayRemoveFlag) {
// display has been removed
changeDockPosition(displayID, @"left");
}
}
}
int main(int argc, const char * argv[])
{
(void)argc;
(void)argv;
@autoreleasepool {
CGDisplayRegisterReconfigurationCallback(displayChanged, NULL);
NSApplicationLoad(); // establish a connection to the window server. In <Cocoa/Cocoa.h>
CFRunLoopRun(); // run the event loop
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.