您的位置:首页 > 其它

osx获取全局键盘/鼠标事件

2011-11-30 14:57 387 查看
下面的代码可以获取osx下的键盘输入,这个是全局的,也就是说在其他Application中输入键盘事件,这些事件也能被捕获。

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


CFRunLoopRef theRL = CFRunLoopGetCurrent();
CFMachPortRef keyUpEventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap ,kCGEventTapOptionListenOnly,CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged),&myCallBack,NULL);
CFRunLoopSourceRef keyUpRunLoopSourceRef = CFMachPortCreateRunLoopSource(NULL, keyUpEventTap, 0);
CFRelease(keyUpEventTap);
CFRunLoopAddSource(theRL, keyUpRunLoopSourceRef, kCFRunLoopDefaultMode);
CFRelease(keyUpRunLoopSourceRef);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: