CGEventTapCreateForPSN in Mavericks+ (GetCurrentProcess deprecated)

守給你的承諾、 提交于 2019-12-03 05:18:07

I think you should subclass NSApplication and override - (void)sendEvent:(NSEvent *)theEvent method for this purpose. From docs:

You rarely should find a real need to create a custom NSApplication subclass. Unlike some object-oriented libraries, Cocoa does not require you to subclass NSApplication to customize app behavior. Instead it gives you many other ways to customize an app.

Also:

IMPORTANT

Many AppKit classes rely on the NSApplication class and may not work properly until this class is fully initialized. As a result, you should not, for example, attempt to invoke methods of other AppKit classes from an initialization method of an NSApplication subclass.

Thus, you can intercept all the events passed though your application and call custom NSApplicationDelegate-inherited protocol methods.

// in SubApplication.h

@protocol ExtendedApplicationDelegate : NSApplicationDelegate

- (void)applicationDidTrapSomeInterestingEvent:(NSEvent *)event;

@end

// in SubApplication.m

- (void)sendEvent:(NSEvent *)event
{
    if ([event type] == NSKeyDown && [event keyCode]==_someCode)
    {
      // call application delegate method
    }
    [super sendEvent:event];
}

I'm not sure if this approach solves the problem but you still make a try.

Another way is to subclass NSApplication and override nextEventMatchingMask:untilDate:inMode:dequeue:. This sees mouse events that are not seen by overriding sendEvent:, e.g., when tracking a scroll bar. I'm not sure if it matters for keyboard events, which the question was about, but it might be of interest to others who stumble on this question.

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