Home > Back-end >  How to make NSOpenPanel accept keyboard and mouse events in objective-c?
How to make NSOpenPanel accept keyboard and mouse events in objective-c?

Time:11-15

I have C console application getting written in XCode, and I need to open a file selector dialog. To do this I'm using Cocoa with objective-c. I'm trying to open an NSOpenPanel to use it for this purpose. I'm using the following code currently:

const char* saveDialog()
{
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    [openDlg setCanChooseFiles:YES];
    [openDlg setFloatingPanel:YES];

    if ( [openDlg runModal] == NSOKButton )
    {
        for( NSURL* URL in [openDlg URLs] )
        {
            NSLog( @"%@", [URL path] );     
            return [URL.path UTF8String];
        }
    }
    
    return NULL;
}

This works, however the created file selector doesnt accept mouse and keyboard events properly. It's hard to explain, but for example when I run the code from XCode when hovering above the window the mouse still behaves as if were in XCode, showing the caret symbol. When i run the application from the terminal whenever I type something it sends the input to the terminal, even though the file selector is "in front". Command clicking gives the mouse events properly to the file selector though.

I looked through NSOpenPanel's documentation and googled the problem extensively but I couldn't find an answer to this.

CodePudding user response:

/*
To run in Terminal: clang openpanel.m -fobjc-arc -framework Cocoa -o openpanel && ./openpanel
*/

#import <Cocoa/Cocoa.h>

int main() {
 NSApplication *application = [NSApplication sharedApplication]; 
 [application setActivationPolicy:NSApplicationActivationPolicyAccessory];
 NSOpenPanel* openDlg = [NSOpenPanel openPanel];
 [openDlg setCanChooseFiles:YES];
 [openDlg setFloatingPanel:YES];

 if ( [openDlg runModal] == NSModalResponseOK ) {
   for( NSURL* URL in [openDlg URLs] ) {
     NSLog( @"%@", [URL path] );     
   }
 }  
 return 0;
}

Thanks to @Willeke.

  • Related