Multiple mice on OS X

后端 未结 6 2195
清歌不尽
清歌不尽 2021-02-01 20:51

I am developing an OS X application that is supposed to take input from two mice. I want to read the motion of each mouse independently. What would be the best way to do this?

6条回答
  •  眼角桃花
    2021-02-01 21:36

    The HID Class Device Interface is definitely what you need. There are basically two steps:

    First you need to find the mouse devices. To do this you need to construct a matching dictionary and then search the IO Registry with it. There is some sample code here, you will need to add some additional elements to the dictionary so you just get the mice instead of the all HID devices on the system. Something like this should do the trick:

    // Set up a matching dictionary to search the I/O Registry by class
    // name for all HID class devices`
    hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
    
    // Add key for device usage page - 0x01 for "Generic Desktop"
    UInt32 usagePage = 0x01;
    CFNumberRef usagePageRef = ::CFNumberCreate( kCFAllocatorDefault, kCFNumberLongType, &usagePage );
    ::CFDictionarySetValue( hidMatchDictionary, CFSTR( kIOHIDPrimaryUsagePageKey ), usagePageRef );
    ::CFRelease( usagePageRef );
    
    // Add key for device usage - 0x02 for "Mouse"
    UInt32 usage = 0x02;
    CFNumberRef usageRef = ::CFNumberCreate( kCFAllocatorDefault, kCFNumberLongType, &usage );
    ::CFDictionarySetValue( hidMatchDictionary, CFSTR( kIOHIDPrimaryUsageKey ), usageRef );
    ::CFRelease( usageRef );
    

    You then need to listen to the X/Y/button queues from the devices you found above. This sample code should point you in the right direction. Using the callbacks is much more efficient than polling!

    The HID code looks much more complex than it is - it's made rather "wordy" by the CF stuff.

提交回复
热议问题