Programmatically Disable Mouse & keyboard

我们两清 提交于 2019-12-19 08:10:39

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/6776660/programmatically-disable-mouse-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!