Skip to content

Instantly share code, notes, and snippets.

@joshwatson
Created March 13, 2019 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshwatson/5e3e1a8d86c78457392ad1fe232589d2 to your computer and use it in GitHub Desktop.
Save joshwatson/5e3e1a8d86c78457392ad1fe232589d2 to your computer and use it in GitHub Desktop.
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