1

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?

4

1 回答 1

0

看起来你的OverlayWindow类继承自NSWindow.
所以你可以使用该makeKeyAndOrderFront:方法。

实际上,您正在使用orderFrontRegardless. 它会有效地将窗口移到前面,但不会使其成为关键窗口。

所以替换:

[ self.overlay orderFrontRegardless ];

经过:

[ self.overlay makeKeyAndOrderFront: nil ];
于 2012-09-23T22:12:54.193 回答