Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Disable Mouse & keyboard

I would like to programmatically disable mouse & keyboard input temporarily on a mac (using Objective C/C/Unix) & then reenable them.

like image 463
Samantha Catania Avatar asked Oct 11 '22 11:10

Samantha Catania


1 Answers

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.

like image 80
FeeJai Avatar answered Oct 14 '22 04:10

FeeJai