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 的任何内容。

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

4

3 回答 3

5

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

于 2014-06-25T12:31:33.053 回答
3

实际上,您可以使用 osascript 无需程序即可轻松完成此操作。

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

但是当您插入电缆时,它不会自动执行此操作。

如果您还想使用单个蓝牙键盘和触控板,那么您可以将它们切换到 macbook,方法是使用 blueutil 暂时禁用 imac 上的蓝牙,以便 macbook 可以抓取键盘和触控板。每当您想退出目标显示模式时,只需关闭我的 macbook 上的蓝牙并等待几秒钟,让 imac 重新连接到键盘和触控板。

在您的 imac 上,将以下脚本放入文件 ~/bin/target-display-mode,然后运行 ​​`chmod +x ~/bin/target-display-mode

然后在您的 imac 上,在术语窗口中,将 target-display-mode 作为命令运行。如果您的 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 或重新启动的情况下重新连接它们。

于 2017-11-18T13:13:09.767 回答
0

想知道你有没有想过这个。我见过的唯一解决方案是运行全屏窗口并像这样触发按键

http://bogner.sh/2013/07/os-x-how-to-use-an-imac-as-monitor/#comment-50925

于 2014-04-22T13:01:04.370 回答