2013-02-21 78 views
8

我使用雷电电缆将MBA附加到iMac。在iMac上按CMD + F2可以使目标显示模式使用iMac作为MBA的显示屏。有没有人有信息如何以编程方式触发该事件?如何以编程方式输入目标显示模式?

我的第一种方法是发送CGEventPostkCGHIDEventTap

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

这是行不通的。它所做的只是一个错误“嘟嘟”。 (也尝试以root用户身份运行)。我认为,kCGHIDEventTap只是错误的目标,CMD + F2可能生活在更高级别的操作系统(又名“某处”)。

运行某些按键事件捕获代码不会显示CMD + F2的任何内容。

有没有人有提示?提前致谢!

+0

我会打赌一美元以上的按键是永远不会到窗口服务器,所以是的,'kCGHIDEventTap'太迟了。您需要回顾一下[IOKit](http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/AccessingHardware/AH_Intro/AH_Intro.html%23/)。我认为[IOHIDManager](http://developer.apple.com/library/mac/#documentation/IOKit/Reference/IOHIDManager_header_reference/Reference/reference。html)将允许你对这些按键进行通知,但是如果你可以在不创建内核扩展的情况下伪造它们,我会感到惊讶。 – 2013-02-21 19:34:32

+0

另请参见:http://www.cocoabuilder.com/archive/cocoa/166322-eject-key-code.html – 2013-03-08 21:07:44

回答

3

我已经开始了一个项目,这样做,即监控iMac和自动触发目标显示模式,以及切换当Macbook连接时关闭蓝牙。您可以从https://github.com/duanefields/VirtualKVM下载它。我正在使用AppleScript触发密钥。

+0

哦,男人,你摇滚!这正是我期待的! – artspb 2015-09-21 10:30:26

+0

这太神奇了!谢谢 – Jimmy 2015-12-18 20:20:24

0

其实你可以很容易地做到这一点,没有一个程序,使用osascript。

osascript -e 'tell application "System Events" to key code 144 using command down' 

但是,插入电缆时它不会自动完成。

如果您还想使用单个蓝牙键盘和触控板,则可以使用blueutil在imac上临时禁用蓝牙以将其切换到macbook,以便macbook可以抓住键盘和触控板。每当你想退出目标显示模式,只需关闭我的MacBook上的蓝牙,并等待几秒钟,imac重新连接到键盘和触控板。

在iMac,把下面的脚本文件中的〜/斌/目标显示方式,并运行`使用chmod + x〜/斌/目标显示模式

然后在你的iMac,在一个术语窗口,运行目标显示模式作为命令。 如果您的Macbook上启用了蓝牙,并且它已经知道您的键盘和触控板,则它将连接到它们。或者打开蓝牙首选项并查找每个设备并“连接”(使用Macbook的内置键盘和触控板)。

#! /usr/bin/env bash 

# Enter target-display mode with a macbook connected by cable; 
# then, temporarily turn off bluetooth so the macbook can the 
# bluetooth keyboard, trackpad and other devices that are currently 
# connected to the imac. 
# 
# Later, turn bluetooth back on so the imac can later reconnect to it's 
# bluetooth devices. 
# 
# To exit target display mode, turn off bluetooth on the macbook and 
# disconnect the cable. After a few seconds, the imac will reconnect to 
# the keyboard and trackpad. 
# 
osascript -e 'tell application "System Events" to key code 144 using command down' 
sleep 5 
(
/usr/local/bin/blueutil off 
sleep 60 
/usr/local/bin/blueutil on 
) & 

发现脚本反过来等待60秒钟,然后在iMac上开启蓝牙回来。这是非常重要的,你没有另一个键盘或硬连线鼠标。如果蓝牙保持关闭,您将无法使用ssh重新连接它们,或重新启动。

相关问题