在未连接到窗口的NSView中使用NSTrackingArea?

时间:2012-03-27 08:01:43

标签: objective-c macos cocoa

基本上,我想要一个覆盖整个屏幕的“隐形”NSView。我将为其添加一个NSTrackingArea,以便在光标在屏幕上移动时获得全局鼠标事件。

-(void)setTrackingArea 
{
    view = [[NSView alloc] initWithFrame:[NSScreen currentScreenForPoint:[NSEvent mouseLocation]].frame];

    NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[NSScreen currentScreenForPoint:[NSEvent mouseLocation]].frame options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways owner:view userInfo:nil];

    [view addTrackingArea:area];

    [area release];

    //[[window contentView] addSubview:view];

    //I don't want to add the view to a window, as all tutorials say.
}

- (void)mouseExited:(NSEvent *)theEvent 
{
    NSLog(@"Exit"); //Never firing
}

这可能吗?在没有窗口的情况下使用NSView和NSTracking区域?

1 个答案:

答案 0 :(得分:2)

使用隐形视图绝对不是您想要做的事情。查看NSEvent上的addGlobalMonitorForEventsMatchingMask::类方法。

例如,以下是为鼠标移动添加监视器的方法:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSMouseMovedMask handler:^(NSEvent *mouseMovedEvent) {
    //do something with that event
}];