NSWindow - 点击外面隐藏窗口

时间:2012-08-18 15:30:52

标签: xcode cocoa nswindow nsstatusitem

我正在为Mac编程做第一步。我只有很少的iOS开发经验。 我需要在菜单栏中构建非常简单的应用程序。 我希望它有点习惯决定使用NSWindow并将其附加到NSStatusItem。

我的AppDelegate看起来如此:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application

    float width = 30.0;
    float height = [[NSStatusBar systemStatusBar] thickness];
    NSRect viewFrame = NSMakeRect(0, 0, width, height);
    statusItem = [[NSStatusItem alloc] init];
    statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:30];
    [statusItem setView:[[TSStatusBarItem alloc] initWithFrame:viewFrame]];


}

- (void)buttonClicked:(int)posx posy:(int)posy {
    [_window setLevel:kCGMaximumWindowLevelKey];
    opened = !opened;
    NSLog(@"Window is shown: %i", opened);

    [_window setFrameTopLeftPoint:NSMakePoint(posx, posy)];

    if(opened == YES) {
        _window.isVisible = YES;
    } else {
        _window.isVisible = NO;
    }

}

这是TSStatusBarItem的代码

- (void)drawRect:(NSRect)rect
{
    // Drawing code here.

    if (clicked) {
        [[NSColor selectedMenuItemColor] set];
        NSRectFill(rect);
    }

    NSImageView *subview = [[NSImageView alloc] initWithFrame:CGRectMake(3, 0, 20, 20)];
    [subview setImage:[NSImage imageNamed:@"icon.png"]];
    [self addSubview:subview];


}

- (void)mouseDown:(NSEvent *)event
{

    NSRect frame = [[self window]frame];
    NSPoint pt = NSMakePoint(NSMinX(frame), NSMinY(frame));
    NSLog(@"X: %f and Y: %f", pt.x, pt.y);

    [self setNeedsDisplay:YES];
    clicked = !clicked;

    [appDelegate buttonClicked:pt.x posy:pt.y];


}

窗口显示和隐藏得非常好,但只有我点击StatusItem。我想添加隐藏窗口的行为,当用户点击外部或在菜单栏中选择另一个项目时(与典型的NSMenu应用程序类似)。

怎么做?如果你有任何想法如何简化我的代码(对不起,我是Mac编码的新手) - 让我们说好。

2 个答案:

答案 0 :(得分:4)

注册NSWindowDidResignKeyNotificationNSWindowDidResignMainNotification,以便在窗口失去焦点时收到通知:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    SEL theSelector = @selector(closeWindow); 
    NSNotificationCenter* theCenter = [NSNotificationCenter defaultCenter]; 
    NSWindow* theWindow = [self window]; 
    [theCenter addObserver:self selector:theSelector name:NSWindowDidResignKeyNotification object:theWindow]; 
    [theCenter addObserver:self selector:theSelector name:NSWindowDidResignMainNotification object:theWindow]; 
}

现在执行以下操作以防窗口失去焦点:

-(void)closeWindow
{
    [[self window] close];
}

或者使用NSPanel自动隐藏,以防焦点丢失。

答案 1 :(得分:0)

-(void)applicationDidResignActive:(NSNotification *)notification
{
    [self window] close];
}

试一试    仅当您的应用处于焦点时,此功能才有效。    并且为了使它成为焦点...也试试这个 - :

[NSApp activateIgnoringOtherApps:YES];