I would like to programmatically disable mouse & keyboard input temporarily on a mac (using Objective C/C/Unix) & then reenable them.
I have made a small open source application that allows you to selectively disable keyboards with the CGEventTap
function from OS X. It is inside the Carbon Framework, but based on CoreFoundation, so it also works on Lion.
As an example you can try my open SourceApp MultiLayout, available here on GitHub.
Basically what you need to do if you want to do it yourself is:
To use it, you need to add the Carbon Framework:
#import <Carbon/Carbon.h>
Then create an event tap like this:
void tap_keyboard(void) {
CFRunLoopSourceRef runLoopSource;
CGEventMask mask = kCGEventMaskForAllEvents;
//CGEventMask mask = CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventKeyDown);
CFMachPortRef eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, mask, myCGEventCallback, NULL);
if (!eventTap) {
NSLog(@"Couldn't create event tap!");
exit(1);
}
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRelease(eventTap);
CFRelease(runLoopSource);
}
To interrupt the events when necessary, use this snippet:
bool dontForwardTap = false;
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
//NSLog(@"Event Tap: %d", (int) CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode));
if (dontForwardTap)
return nil;
else
return event;
}
Just set the boolean dontForwardTap
to true, and the events will be stopped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With