问题描述
我试图使用CGCreateEventTap来监控全局鼠标点击,但是当我这样做,似乎阻止与我自己的应用程序的交互。其他运行的应用程序中的鼠标点击工作正常,但我自己的应用程序(即DemoAppDelegate应用程序)不会完全响应。我可以拖动应用程序的主窗口,但红色/黄色/绿色窗口按钮是灰色的。 DemoApp的菜单也是不可点击的。
I'm trying to use CGCreateEventTap to monitor global mouse clicks, however when I do this it seems to block interaction with my own app. Mouse clicks in other running apps work fine, but my own app (that is the DemoAppDelegate app) does not respond completely. I can drag the main window for the app, but the red/yellow/green window buttons are greyed out. And the DemoApp's menu is unclickable as well.
这似乎对我很奇怪,我一直无法想出来。使用事件抽头的例子很少,很多,所以任何建议都非常感谢。
This seems really strange to me, and I've been unable to figure it out. Examples of using event taps are few and far between, so any advice is greatly appreciated.
#import "DemoAppDelegate.h"
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
CGPoint location = CGEventGetLocation(event);
NSLog(@"location: (%f, %f) - %@\n", location.x, location.y, (NSString*)refcon);
return event;
}
@implementation DemoAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
CFMachPortRef eventTap;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
eventMask = 1 << kCGEventLeftMouseDown;
eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap,
1, eventMask, myCGEventCallback, @"mydata");
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource,
kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRunLoopRun();
}
@end
推荐答案
当创建Cocoa应用程序时, - [NSApplication run]
负责运行事件循环 - 它运行运行循环,并分派事件。这意味着您应该删除
When you create a Cocoa application, -[NSApplication run]
is responsible for running the event loop — it runs the run loop, and dispatches events. This means that you should remove that
CFRunLoopRun();
在底部调用-applicationDidFinishLaunching:
方法实现,因为它阻止 -applicationDidFinishLaunching:
从返回并且阻止 NSApplication
调度事件。
call at the bottom of your -applicationDidFinishLaunching:
method implementation, since it prevents -applicationDidFinishLaunching:
from returning and also prevents NSApplication
from dispatching events.
这篇关于CGEventTap阻止应用程序输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!