开发者

Programmatically Disable Mouse & keyboard

开发者 https://www.devze.com 2023-03-21 19:28 出处:网络
I would like to programma开发者_JAVA百科tically disable mouse & keyboard input temporarily on a mac (using Objective C/C/Unix) & then reenable them.I have made a small open source application

I would like to programma开发者_JAVA百科tically 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消