以编程方式禁用鼠标和键盘 [英] Programmatically Disable Mouse & keyboard

查看:299
本文介绍了以编程方式禁用鼠标和键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式禁用鼠标&暂时在Mac上使用键盘输入(使用Objective C/C/Unix)&然后重新启用它们.

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

推荐答案

我制作了一个小型的开源应用程序,该应用程序允许您使用OS X中的CGEventTap功能有选择地禁用键盘.它位于Carbon框架内,但是基于CoreFoundation,因此它也适用于Lion. 例如,您可以尝试使用我的开放SourceApp MultiLayout,可在GitHub上找到.

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:

要使用它,您需要添加Carbon框架:

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;
}

只需将布尔值dontForwardTap设置为true,事件就会停止.

Just set the boolean dontForwardTap to true, and the events will be stopped.

这篇关于以编程方式禁用鼠标和键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆