【发布时间】:2012-03-08 06:55:27
【问题描述】:
在 Mac OS / Cocoa 中,我可以合成键盘条目 - 字符串 - 以透明方式用于最前面的应用程序吗?
更准确地说,我不想发送特殊字符或控制序列。我唯一需要的是发送标准字符。
刚刚了解到here,AppleScript 可以做到这一点:
tell application "TextEdit"
activate
tell application "System Events"
keystroke "f" using {command down}
end tell
end tell
问:我将如何使用 ObjC / cocoa 做到这一点?
2012-02-18 更新 - 尼克斯提案增强
基于Nick下面的代码,这里是最终的解决方案:
// First, get the PSN of the currently front app
ProcessSerialNumber psn;
GetFrontProcess( &psn );
// make some key events
CGEventRef keyup, keydown;
keydown = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)6, true);
keyup = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)6, false);
// forward them to the frontmost app
CGEventPostToPSN (&psn, keydown);
CGEventPostToPSN (&psn, keyup);
// and finally behave friendly
CFRelease(keydown);
CFRelease(keyup);
使用此方法,单击非激活面板的按钮会将事件定位到实际的前端应用程序。完全是我想做的事。
【问题讨论】:
标签: objective-c macos cocoa