如何激活窗口或有焦点?

时间:2012-09-23 17:49:04

标签: objective-c macos cocoa

我有以下代码创建无边框叠加层:

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

这一切都运作良好。创建了叠加层,我可以捕获键盘事件。但是,我必须首先点击叠加层以使其聚焦或使其处于活动状态,即使我的应用程序在我启动叠加层时处于焦点时也是如此。任何想法如何创建叠加层,使其处于焦点,以便键盘事件可以工作,而不必先点击叠加层?

1 个答案:

答案 0 :(得分:0)

您的OverlayWindow类似乎继承自NSWindow 因此,您可以使用makeKeyAndOrderFront:方法。

实际上,您使用的是orderFrontRegardless。它会有效地将窗口移到前面,但它不会成为窗口。

所以替换:

[ self.overlay orderFrontRegardless ];

由:

[ self.overlay makeKeyAndOrderFront: nil ];