Search code examples
objective-ccocoaosx-mountain-lion

How to programmatically enter target display mode?


I've attached a MBA to an iMac using a thunderbolt cable. Pressing CMD+F2 on the iMac enables the target display mode to use the iMac as display for the MBA. Does anyone have information how to trigger that event programmatically?

My first approach was to send a CGEventPost to kCGHIDEventTap

CGEventRef f2CommandDown = CGEventCreateKeyboardEvent(src, (CGKeyCode)120, YES);
CGEventSetFlags(f2CommandDown, kCGEventFlagMaskCommand);
CGEventRef f2CommandUp = CGEventCreateKeyboardEvent(src, (CGKeyCode)120, NO);
CGEventPost(kCGHIDEventTap, f2CommandDown);
CGEventPost(kCGHIDEventTap, f2CommandUp);

That doesn't work. All it does is an error "beep". (tried running as root user too). I think, kCGHIDEventTap is just the wrong target and CMD+F2 might live in a higher level of the OS (aka. "somewhere")

Running some key-event capturing code doesn't show anything for CMD+F2.

Does anyone have a hint? Thanks in advance!


Solution

  • I've started a project that does this, namely monitor the iMac and automatically trigger target display mode and toggle off bluetooth when a Macbook is connected. You can download it from https://github.com/duanefields/VirtualKVM. I'm using AppleScript to trigger the keys.