首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在UI应用程序中使用CFRunLoop

在UI应用程序中使用CFRunLoop
EN

Stack Overflow用户
提问于 2011-02-17 05:46:30
回答 1查看 1K关注 0票数 0

我已经从我写的一个控制台应用程序中获得了一些代码,我试图适应在基于UI的应用程序中使用。它注册一个事件陷阱来监控系统范围内的鼠标移动。有人建议我创建并运行一个线程来设置事件循环,这样我就不会阻塞应用程序(代码是从applicationDidFinishLaunching调用的)。

老实说,我看过一些关于运行循环的文档,我完全搞混了:-(我的代码只是挂在对listen函数的调用中。

代码语言:javascript
复制
static MouseListener* listener = nil;

CGEventRef eventOccurred(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void* refcon) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    event = [listener eventOccurred:proxy:type:event:refcon];

    [pool release];

    return event;
}


@implementation MouseListener

-(MouseListener*) myinit {
    if (self = [super init]) {
        eventThread = [[NSThread alloc] initWithTarget:self                              
                                              selector:@selector(listen:)                              
                                                object:nil];        
        [eventThread start];
    }   

    return self;
}

-(void)listen:(NSObject*) object {        
    if (!listener) {
        listener = self;  

        CFMachPortRef tap = CGEventTapCreate(kCGHIDEventTap, 
                                             kCGHeadInsertEventTap, 
                                             kCGEventTapOptionDefault, 
                                             NSAnyEventMask, 
                                             eventOccurred, 
                                             NULL);

        if (tap) {
            CFRunLoopRef loop = CFRunLoopGetCurrent(); 
            CFRunLoopSourceRef src = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0);
            CFRunLoopAddSource(loop, src, kCFRunLoopCommonModes);
            CGEventTapEnable(tap, true);
            //CFRunLoopRun();
            //[[NSRunLoop currentRunLoop] run];
            CFRelease(src);
            CFRelease(tap);
       }
    }
}

-(CGEventRef) eventOccurred:(CGEventTapProxy) proxy: (CGEventType) type: (CGEventRef) event: (void*) refcon {

    // Do stuff, never gets called

    return event;
}
EN

回答 1

Stack Overflow用户

发布于 2011-02-22 19:58:02

回到家后,我需要检查我的代码,但您的代码看起来没问题(我也做过类似的检查,但改为侦听I/O Kit事件)。CFRunLoopRun()是你想要调用的函数,但是,你为什么不把你的事件点击添加到你的应用程序的主运行循环中呢?这也避免了任何线程恶作剧。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5022518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档