如何在OSX中点击/挂钩键盘事件并记录哪个键盘触发每个事件

时间:2015-05-21 17:19:58

标签: macos hook keyboard-events tap iokit

我现在已经发现如何在OS X上以低级别挂机/点击键盘事件:How to tap (hook) F7 through F12 and Power/Eject on a MacBook keyboard

打印出该答案的代码:

// compile and run from the commandline with:
//    clang  -framework coreFoundation  -framework IOKit  ./HID.c  -o hid
//    sudo ./hid

// This code works with the IOHID library to get notified of keys.
//   Still haven't figured out how to truly intercept with
//   substitution.

#include <IOKit/hid/IOHIDValue.h>
#include <IOKit/hid/IOHIDManager.h>

void myHIDKeyboardCallback( void* context,  IOReturn result,  void* sender,  IOHIDValueRef value )
{
    IOHIDElementRef elem = IOHIDValueGetElement( value );

    if (IOHIDElementGetUsagePage(elem) != 0x07)
        return;

    uint32_t scancode = IOHIDElementGetUsage( elem );

    if (scancode < 4 || scancode > 231)
        return;

    long pressed = IOHIDValueGetIntegerValue( value );

    printf( "scancode: %d, pressed: %ld\n", scancode, pressed );
}


CFMutableDictionaryRef myCreateDeviceMatchingDictionary( UInt32 usagePage,  UInt32 usage )
{
    CFMutableDictionaryRef dict = CFDictionaryCreateMutable(
                                                            kCFAllocatorDefault, 0
                                                        , & kCFTypeDictionaryKeyCallBacks
                                                        , & kCFTypeDictionaryValueCallBacks );
    if ( ! dict )
        return NULL;

    CFNumberRef pageNumberRef = CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, & usagePage );
    if ( ! pageNumberRef ) {
        CFRelease( dict );
        return NULL;
    }

    CFDictionarySetValue( dict, CFSTR(kIOHIDDeviceUsagePageKey), pageNumberRef );
    CFRelease( pageNumberRef );

    CFNumberRef usageNumberRef = CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, & usage );

    if ( ! usageNumberRef ) {
        CFRelease( dict );
        return NULL;
    }

    CFDictionarySetValue( dict, CFSTR(kIOHIDDeviceUsageKey), usageNumberRef );
    CFRelease( usageNumberRef );

    return dict;
}


int main(void)
{
    IOHIDManagerRef hidManager = IOHIDManagerCreate( kCFAllocatorDefault, kIOHIDOptionsTypeNone );

    CFArrayRef matches;
    {
        CFMutableDictionaryRef keyboard = myCreateDeviceMatchingDictionary( 0x01, 6 );
        CFMutableDictionaryRef keypad   = myCreateDeviceMatchingDictionary( 0x01, 7 );

        CFMutableDictionaryRef matchesList[] = { keyboard, keypad };

        matches = CFArrayCreate( kCFAllocatorDefault, (const void **)matchesList, 2, NULL );
    }

    IOHIDManagerSetDeviceMatchingMultiple( hidManager, matches );

    IOHIDManagerRegisterInputValueCallback( hidManager, myHIDKeyboardCallback, NULL );

    IOHIDManagerScheduleWithRunLoop( hidManager, CFRunLoopGetMain(), kCFRunLoopDefaultMode );

    IOHIDManagerOpen( hidManager, kIOHIDOptionsTypeNone );

    CFRunLoopRun(); // spins
}

我如何(可能会调整该代码)识别哪个键盘负责特定事件?

用例是我计划使用外部键盘重新映射,但同时保留内置MacBook键盘的原始映射。

编辑:
OSX HID Filter for Secondary Keyboard?
https://github.com/candera/khordr/blob/master/src/c/keygrab/hid-scratch.c
http://ianjoker.googlecode.com/svn/trunk/Joker/Joker/hid_test.cpp
http://www.cplusplusdevelop.com/72_17345226/
http://www.cocoabuilder.com/archive/cocoa/229902-which-keyboard-barcode-scanner-did-the-event-come-from.html

2 个答案:

答案 0 :(得分:2)

我正在研究这个问题,最后得到了解决方案。 OP的代码是正确的,如果您想要键盘/打击垫的产品ID,请在myHIDKeyboardCallback()功能中添加行:

void myHIDKeyboardCallback(void* context,  IOReturn result,  void* sender,  IOHIDValueRef value){

    IOHIDElementRef elem = IOHIDValueGetElement(value);
    if (IOHIDElementGetUsagePage(elem) != 0x07)
        return;

    IOHIDDeviceRef device = sender;
    int32_t pid = 1;
    CFNumberGetValue(IOHIDDeviceGetProperty(device, CFSTR("idProduct")), kCFNumberSInt32Type, &pid);

    uint32_t scancode = IOHIDElementGetUsage(elem);

    if (scancode < 4 || scancode > 231)
        return;

    long pressed = IOHIDValueGetIntegerValue(value);

    printf("scancode: %d, pressed: %ld, keyboardId=%d\n", scancode, pressed, pid);
}

正如@pmdj所说你可以使用IOHIDDeviceRegisterInputValueCallback(),我遇到了麻烦,发现sender参数无论如何都提供了键盘产品ID。

答案 1 :(得分:1)

如果您使用IOHIDDeviceRegisterInputValueCallback在每个感兴趣的设备上单独注册回调,则sender参数将为IOHIDDeviceRef,表示该设备。 (而不是使用IOHIDManagerRegisterInputValueCallback,其中发件人将是HID经理参考)

唯一的缺点是,您需要注册并处理匹配设备的热插拔事件通知。 (每当出现新设备时注册,并在设备消失时注销)

您可以使用IOHIDDeviceCreate()获取HID设备引用 - 这需要io_service_t作为参数。这反过来意味着您需要使用标准的IOKit IOService匹配函数来获取和查看您的设备列表,但您确实可以获得单个设备的明确列表,您可以查询要显示给用户的名称等。关键功能是IOServiceAddMatchingNotification