如何在可可中捕获全球keydown / keyup事件 [英] How to trap global keydown/keyup events in cocoa

查看:166
本文介绍了如何在可可中捕获全球keydown / keyup事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的可可应用程序中捕获,修改和转移系统中的所有keydown / keyup事件。我知道CGEventTapCreate,但是没有找到任何来自net的工作代码。

I want to trap, modify and divert all the keydown/keyup events in the system within my cocoa app. I know about CGEventTapCreate but, didn't found any working code from net.

谢谢

推荐答案

找到解决方案:

self.machPortRef =  CGEventTapCreate(kCGSessionEventTap,
                                             kCGTailAppendEventTap,
                                             kCGEventTapOptionDefault,
                                             CGEventMaskBit(kCGEventKeyDown),
                                             (CGEventTapCallBack)eventTapFunction,
                                             self);
        if (self.machPortRef == NULL)
        {
            printf("CGEventTapCreate failed!\n");
        } else {
            self.eventSrc = CFMachPortCreateRunLoopSource(NULL, self.machPortRef, 0);
            if ( self.eventSrc == NULL )
            {
                printf( "No event run loop src?\n" );
            }else {
                CFRunLoopRef runLoop =  CFRunLoopGetCurrent(); //GetCFRunLoopFromEventLoop(GetMainEventLoop ()); 

                // Get the CFRunLoop primitive for the Carbon Main Event Loop, and add the new event souce
                CFRunLoopAddSource(runLoop, self.eventSrc, kCFRunLoopDefaultMode);

            }
        }

属性:

CFMachPortRef machPortRef;
CFRunLoopSourceRef  eventSrc;

事件处理程序:

 CGEventRef eventTapFunction(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
    //printf("eventTap triggered\n");
    return event;
}

这篇关于如何在可可中捕获全球keydown / keyup事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆