I would like to filter keyboard input on a second keyboard, and prevent the key events for that second keyboard from reaching the OS (handle them myself). How can this be done?
Asked
Active
Viewed 2,078 times
2 Answers
7
It can be done by using IOKit and the HIDManager class.
If exclusive access to the keyboard is desired, the kIOHIDOptionsTypeSeizeDevice
option can be used, but the program will have to be run with root privileges.
A stub of the code required to obtain this result is shown below:
// Create a manager instance
IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDManagerOptionNone);
if (CFGetTypeID(manager) != IOHIDManagerGetTypeID()) {
exit(1);
}
// Setup device filtering using IOHIDManagerSetDeviceMatching
//matchingdict = ...
IOHIDManagerSetDeviceMatching(manager, matchingdict);
// Setup callbacks
IOHIDManagerRegisterDeviceMatchingCallback(manager, Handle_DeviceMatchingCallback, null);
IOHIDManagerRegisterDeviceRemovalCallback(manager, Handle_RemovalCallback, null);
IOHIDManagerRegisterInputValueCallback(manager, Handle_InputCallback, null);
// Open the manager and schedule it with the run loop
IOHIDManagerOpen(manager, kIOHIDOptionsTypeSeizeDevice);
IOHIDManagerScheduleWithRunLoop(manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
// Start the run loop
//...
More detailed information can be found in the Apple docs over here: http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/HID/new_api_10_5/tn2187.html
The complete code I used for my application can be found here: https://gist.github.com/3783042

GaretJax
- 7,462
- 1
- 38
- 47
-
Thanks a lot! I don't know how, but I didn't get notification that this question was answered. Im glad to finally know how to do this. I tried out your sample code and it worked like a charm. – JayGee Mar 13 '14 at 23:12
-1
I am going to take a stab at this but short of writing your own driver, you can't intercept the buffer. This is to prevent keyloggers and other malicious programs. Everything has to go though the OS.

AnthonyFG
- 68
- 8
-
1Wrong: You can use the userland HID interface and kIOHIDOptionsTypeSeizeDevice to get exclusive access to a device without the need of a kext. If you don't need exclusive access, the program doesn't even have to be run with root privileges. – GaretJax Sep 27 '12 at 07:36
-
I am wrong, you should post as an answer, but in self educating I found it does require root access for keyboards only – AnthonyFG Sep 27 '12 at 14:10
-
You're right, but only for exclusive access, as I already wrote in my comment as well ;) – GaretJax Sep 28 '12 at 07:28