简体   繁体   English

MacOS:如何启动 gui QProcess 并将其置于最前面?

[英]MacOS: How to launch gui QProcess and bring it to front?

I'm trying to run gui application with QProcess, but it is not active by default:我正在尝试使用 QProcess 运行 gui 应用程序,但默认情况下它是不活动的:

qint64 pid = 0;
QProcess::startDetached(executable, args, wd, &pid); //The app is in background

I tried activateWithOptions and it doesn't help:我试过activateWithOptions但它没有帮助:

qint64 pid = 0;
QProcess::startDetached(executable, args, wd, &pid);

NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:static_cast<pid_t>(pid)];
[app activateWithOptions: NSApplicationActivateIgnoringOtherApps]; //The app is still in background

But if I add a small delay activateWithOptions works as expected:但是,如果我添加一个小的延迟, activateWithOptions会按预期工作:

qint64 pid = 0;
QProcess::startDetached(executable, args, wd, &pid);

QThread::msleep(2000);
NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:static_cast<pid_t>(pid)];
[app activateWithOptions: NSApplicationActivateIgnoringOtherApps]; //The app is in foreground!

But QThread::msleep(2000) looks like a dirty hack, and is not going to pass code review:)但是QThread::msleep(2000)看起来像是一个肮脏的 hack,并且不会通过代码审查:)

So, my question is: How to start gui process and bring it to front without hacks?所以,我的问题是:如何启动 gui 进程并将其带到前面而不会受到黑客攻击?

PS: I know that QProcess::startDetached("open", "-a " + executable); PS:我知道QProcess::startDetached("open", "-a " + executable); might work, but it doesn't let specify working directory, so it doesn't suit me可能有用,但它不允许指定工作目录,所以它不适合我

UPD: Seems like I need to wait until the application finished launching , and then I'll be able to activate it. UPD:好像我需要等到应用程序完成启动,然后我才能激活它。

My solution:我的解决方案:

    NSRunningApplication *waitForAppHandle(pid_t pid) const
    {
        forever {
            NSRunningApplication *app  = [NSRunningApplication runningApplicationWithProcessIdentifier: pid];
            if (app) 
                return app;
            }

            QThread::yieldCurrentThread();
        }
    }

    bool waitForLaunched(NSRunningApplication *app) const
    {

        forever {
            if ([app isFinishedLaunching]) {
                return;
            }

            QThread::yieldCurrentThread();
        }
    }

    void activate(pid_t pid)
    {
        NSRunningApplication *app = waitForAppHandle();
        waitForLaunched(app);

        [app activateWithOptions : NSApplicationActivateIgnoringOtherApps];
    }

    //...
    
    QProcess p;
    //...
    activate(p.processId());

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

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