2011-04-26 58 views
0

道歉,如果这是一个愚蠢/简单的问题,但仍然习惯了Mac领域的一切。用运行循环重写main.m,但仍然进入NSApplicationMain调用?

戴夫是一种足以回答我在这里一个问题: Modify NSEvent to send a different key than the one that was pressed

这导致了下面的代码,它的伟大工程:

#import <Cocoa/Cocoa.h> 

CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { 
    //0x0b is the virtual keycode for "b" 
    //0x09 is the virtual keycode for "v" 
    if (CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode) == 0x0B) { 
     CGEventSetIntegerValueField(event, kCGKeyboardEventKeycode, 0x09); 
    } 

    return event; 
} 

int main(int argc, char *argv[]) { 
    //return NSApplicationMain(argc, (const char **)argv); 

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    CFRunLoopSourceRef runLoopSource; 

    CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, kCGEventMaskForAllEvents, myCGEventCallback, NULL); 

    if (!eventTap) { 
     NSLog(@"Couldn't create event tap!"); 
     exit(1); 
    } 

    runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0); 

    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); 

    CGEventTapEnable(eventTap, true); 

    CFRunLoopRun(); 

    CFRelease(eventTap); 
    CFRelease(runLoopSource); 
    [pool release]; 

    exit(0); 
} 

由于一些有用的错误信息(不能有两个“主要”方法)我发现我必须将这些代码放在main.m文件中(对吧?)。这意味着我正在覆盖默认方法:

int main(int argc, char *argv[]) { 
    return NSApplicationMain(argc, (const char **)argv); 
} 

这意味着我的其他基于Objective-C的代码都没有触发。但是,如果我取消注释该位(或者尝试调用NSApplicationMain),那么main.m运行循环是不运行的。

我想这对于一个经验丰富的Mac小伙子来说相当简单,但是我很难把头围绕在它周围。谢谢。

回答

1

我看不到任何理由为什么相同的想法不会在你的代码中的其他地方工作。你可以把它放在你的应用代理的-applicationDidFinishLaunching:方法中吗?如果这样做,您将不需要0​​调用,因为运行循环已经在运行。你也不需要autorelease池位。