模拟组合击键不起作用?

时间:2013-10-10 05:08:06

标签: objective-c c xcode macos cocoa

我想在finder中模拟“cmd + k”keystorke,以便它可以打开“连接到服务器窗口”。但它没有用。我是客观C的新手所以任何人都可以帮助我。我试过下面的代码,但不知道它为什么不起作用。

CGEventSourceRef src = 
CGEventSourceCreate(kCGEventSourceStateHIDSystemState);

CGEventRef cmdd = CGEventCreateKeyboardEvent(src, 0x37, true);
CGEventRef cmdu = CGEventCreateKeyboardEvent(src, 0x37, false);
CGEventRef k_d = CGEventCreateKeyboardEvent(src, 0x4F, true);
CGEventRef k_u = CGEventCreateKeyboardEvent(src, 0x4F, false);

CGEventSetFlags(k_d, kCGEventFlagMaskCommand);
CGEventSetFlags(k_u, kCGEventFlagMaskCommand);

CGEventTapLocation loc = kCGHIDEventTap; // kCGSessionEventTap also works
CGEventPost(loc, cmdd);
CGEventPost(loc, k_d);
CGEventPost(loc, k_u);
CGEventPost(loc, cmdu);

CFRelease(cmdd);
CFRelease(cmdu);
CFRelease(k_d);
CFRelease(k_u);
CFRelease(src);  

提前致谢...

1 个答案:

答案 0 :(得分:1)

首先我写了小苹果脚本,然后在可可内部调用相同的内容,请尝试以下: -

NSBundle *def=[NSBundle mainBundle];
NSString *path=[def pathForResource:@"openServer" ofType:@"scpt"];
NSAppleScript *appleScript=[[NSAppleScript alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
[appleScript executeAndReturnError:nil];

以下是名称为openServer.scpt

的applescript文件
tell application "Finder"
    activate
    tell application "System Events"
        keystroke "k" using command down
    end tell
end tell