我正在做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编程的新手)-让我们说吧。
发布于 2012-08-18 16:31:21
注册NSWindowDidResignKeyNotification
或NSWindowDidResignMainNotification
,以便在窗口失去焦点时收到通知:
- (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
,它会在焦点丢失的情况下自动隐藏。
发布于 2017-03-22 12:08:09
-(void)applicationDidResignActive:(NSNotification *)notification
{
[self window] close];
}
试一下只有当你的应用程序处于焦点状态时才会起作用。为了让它聚焦..。也试试这个- :
NSApp激活:是;
发布于 2021-09-23 08:46:04
@Anne答案的Swift 5版本:
NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification, object: nil, queue: OperationQueue.main) { _ in
self.window?.close()
}
NotificationCenter.default.addObserver(forName: NSWindow.didResignMainNotification, object: nil, queue: OperationQueue.main) { _ in
self.window?.close()
}
https://stackoverflow.com/questions/12019808
复制相似问题