简体   繁体   English

如何让 NSOpenPanel 在 Objective-C 中接受键盘和鼠标事件?

[英]How to make NSOpenPanel accept keyboard and mouse events in objective-c?

I have C++ console application getting written in XCode, and I need to open a file selector dialog.我有用 XCode 编写的 C++ 控制台应用程序,我需要打开一个文件选择器对话框。 To do this I'm using Cocoa with objective-c.为此,我将 Cocoa 与 Objective-c 一起使用。 I'm trying to open an NSOpenPanel to use it for this purpose.我正在尝试打开一个 NSOpenPanel 以将其用于此目的。 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.很难解释,但例如,当我在窗口上方悬停时从 XCode 运行代码时,鼠标仍然表现得好像在 XCode 中一样,显示插入符号。 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.我查看了 NSOpenPanel 的文档并广泛搜索了这个问题,但我找不到答案。

/*
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.感谢@Willeke。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM