Objective c 为最前端的应用程序生成键盘事件
在Mac OS/Cocoa中,我可以以透明的方式合成最前端应用程序的键盘输入项吗 更准确地说,我不想发送特殊字符或控制序列。我只需要发送标准字符 刚刚了解到,AppleScript可以实现以下功能:Objective c 为最前端的应用程序生成键盘事件,objective-c,macos,cocoa,Objective C,Macos,Cocoa,在Mac OS/Cocoa中,我可以以透明的方式合成最前端应用程序的键盘输入项吗 更准确地说,我不想发送特殊字符或控制序列。我只需要发送标准字符 刚刚了解到,AppleScript可以实现以下功能: tell application "TextEdit" activate tell application "System Events" keystroke "f" using {command down} end tell end tell Q:我如何
tell application "TextEdit"
activate
tell application "System Events"
keystroke "f" using {command down}
end tell
end tell
Q:我如何使用ObjC/cocoa实现这一点?
更新2012-02-18-改进了Nicks提案
根据下面的代码,以下是最终解决方案:
// 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);
使用此方法,单击非激活面板的按钮将事件定向到实际的前端应用程序。这正是我想要做的。当然,您会希望使用CGEventCreateKeyboardEvent创建键盘事件,然后将其作为如下内容发布:
CGEventRef keyup, keydown;
keydown = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, true);
keyup = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, false);
CGEventPost(kCGHIDEventTap, keydown);
CGEventPost(kCGHIDEventTap, keyup);
CFRelease(keydown);
CFRelease(keyup);
它比AppleScript复杂一点,但它确实做到了。您确实需要显式地发布一个keydown和一个keydup事件。更多信息请访问。谢谢!从来没有做过这么低水平的事情。