I have the following code that creates a borderless overlay:
AppDelegate.m
NSRect frame = [[NSScreen mainScreen] frame];
self.overlay = [[OverlayWindow alloc] initWithContentRect:frame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[self.overlay setAcceptsMouseMovedEvents:YES];
[self.overlay setOpaque:NO];
[self.overlay setLevel:CGShieldingWindowLevel()];
[self.overlay setBackgroundColor:[NSColor colorWithDeviceRed:0.0 green:0.0 blue:0.0 alpha:0.75]];
// Create the subview
OverlayView *subview = [[OverlayView alloc] initWithFrame:NSZeroRect];
[[self.overlay contentView] addSubview:subview];
[self.overlay setContentView:subview];
[self.overlay makeFirstResponder:subview];
[self.overlay orderFrontRegardless];
OverlayWindow.m
@implementation OverlayWindow
// need this so that we can accept mouse events in our view
// we want to use NSBorderlessWindowMask for this window, and that prevents us from
// becoming a key window and thus mouse events don't work
- (BOOL)canBecomeKeyWindow
{
return YES;
}
- (BOOL)canBecomeMainWindow
{
return YES;
}
@end
OverlayView.m
@implementation OverlayView
- (BOOL)acceptsFirstResponder {return YES;}
- (BOOL)resignFirstResponder {
self.needsDisplay = YES;
return YES;
}
- (BOOL)becomeFirstResponder {return YES;}
- (BOOL)canBecomeKeyWindow {return YES;}
...
- (void)keyDown:(NSEvent *)theEvent {
switch (theEvent.keyCode) {
case 53:
[[self window] close];
break;
default:
break;
}
}
@end
And this all works well. The overlay is created, and I can capture keyboard events. However I have to click on the overlay first to give it focus or make it active, even though my app was in focus when I launched the overlay. Any ideas how to create the overlay such that it will be in focus so that the keyboard events will work without having to click on the overlay first?