osx获取 键盘 鼠标 输入

Submitted by lepton on Tue, 05/10/2016 - 17:49

Tags

获取osx下的键盘输入

NSKeyDown事件需要 申请权限

(System Preferences → Security & Privacy → Accessibility)

 

    NSDictionary *dict=@{(__bridge NSString *)kAXTrustedCheckOptionPrompt:@YES};
    BOOL istrue=AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef)dict);
    NSLog(@"%d",istrue);

方法1 cocoa

[NSEvent addGlobalMonitorForEventsMatchingMask:NSRightMouseDownMask|NSKeyDownMask|NSFlagsChanged handler:^(NSEvent * _Nonnull event) {
        if (event.type==NSKeyDown){
            NSLog(@"event %@",event.characters);
        }
    }];
   

方法2 carbon

引用 http://blog.csdn.net/tjsjping/article/details/7027254

CFRunLoopRef theRL = CFRunLoopGetCurrent();
    CFMachPortRef keyUpEventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap ,kCGEventTapOptionListenOnly,CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventFlagsChanged),&myCallBack,NULL);
    CFRunLoopSourceRef keyUpRunLoopSourceRef = CFMachPortCreateRunLoopSource(NULL, keyUpEventTap, 0);
    CFRelease(keyUpEventTap);
    CFRunLoopAddSource(theRL, keyUpRunLoopSourceRef, kCFRunLoopDefaultMode);
    CFRelease(keyUpRunLoopSourceRef); CGEventRef myCallBack(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *userInfo)
{
    
    UniCharCount actualStringLength = 0;
    UniChar inputString[128];
    CGEventKeyboardGetUnicodeString(event, 128, &actualStringLength, inputString);
    NSString* inputedString = [[NSString alloc] initWithBytes:(const void*)inputString length:actualStringLength encoding:NSUTF8StringEncoding];
    
    CGEventFlags flag = CGEventGetFlags(event);
    NSLog(@"inputed string:%@, flags:%lld", inputedString, flag);
    return event;
}

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.