Search code examples
objective-ccocoanswindow

Create NSWindow from the command line tool


I want to write a command-line tool which will display window in certain situations (but not always). Now I'm trying to create a simple application which just displays a window. I need it to behave like any other window (but without main menu). I need icon to appear in the Dock.

Right now I've come with some code that follows below. But this code creates a window that behave strange. I commented out level = 1 line. With this line this windows appears on top of other windows. Without this line this window appears below other windows and I can't bring it to the top. Also it does not set cursor properly, e.g. I can move cursor from textbox to this app and the cursor keeps text appearance even when hovering over title or other parts of this window. I feel like I missing some important part of the puzzle.

#import <AppKit/AppKit.h>

@interface ApplicationDelegate : NSObject <NSApplicationDelegate>
@end

int main(int argc, const char * argv[]) {
    NSApplication *application = [NSApplication sharedApplication];
    ApplicationDelegate *applicationDelegate = [[ApplicationDelegate alloc] init];
    application.delegate = applicationDelegate;
    [application run];
    return 0;
}

@implementation ApplicationDelegate {
    NSWindow *window;
}
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
    window = [
        [NSWindow alloc]
        initWithContentRect:NSMakeRect(100, 100, 600, 400)
        styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable
        backing:NSBackingStoreBuffered
        defer:NO
    ];
    window.title = @"My Title";
//    window.level = 1;
    [window makeKeyAndOrderFront:nil];
}

@end

Solution

  • Apparently I needed the following line in main function:

        application.activationPolicy = NSApplicationActivationPolicyRegular;
    

    With this line I'm getting Dock icon and proper behaviour for the window.