Still have not received an answer in the comments, but since it may help other people in the future, I decided to answer anyway.
With IOKit, you can detect that there is a device on the keyboard and receive key events, such as device events. I used this to detect joystick events, but it should work well with keyboards. I assume that the modifications I made are sufficient and should work, however, my Xcode is being updated now, so I have not been able to test it yet.
KeyboardWatcher.h File:
#import <Foundation/Foundation.h> #import <IOKit/hid/IOHIDManager.h> #import <IOKit/hid/IOHIDKeys.h> @interface KeyboardWatcher : NSObject{ IOHIDManagerRef HIDManager; } @property (nonatomic) int keysPressedCount; +(instancetype)sharedWatcher; -(void)startWatching; -(void)stopWatching; @end
KeyboardWatcher.m File:
#import "KeyboardWatcher.h" @implementation KeyboardWatcher static KeyboardWatcher *_sharedWatcher; +(instancetype)sharedWatcher { @synchronized([self class]) { if (!_sharedWatcher){ _sharedWatcher = [[KeyboardWatcher alloc] init]; } return _sharedWatcher; } return nil; } -(instancetype)init { self = [super init]; if (self){ self.keysPressedCount = 0; } return self; } -(void)startWatching { [self watchDevicesOfType:kHIDUsage_GD_Keyboard]; } -(void)watchDevicesOfType:(UInt32)deviceType {
If you want to determine which unique identifier is the key, you can use these enumerations (instead of importing Carbon, you can simply create the CGKeyboardMapping.h file and paste them there): fooobar.com/questions/100187 / ...
Finally, to use it, you just need to do this to start viewing keyboard events:
[[KeyboardWatcher sharedWatcher] startWatching];
Get the number of keys pressed using:
[[KeyboardWatcher sharedWatcher] keysPressedCount];
And to stop:
[[KeyboardWatcher sharedWatcher] stopWatching];
These were my links to my original joystick code:
As soon as the update is completed, I will run the code and let me know if it works or not.
EDIT: Just tested and working. Remember to add the IOKit infrastructure to the project.