简体   繁体   中英

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:

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

I tried activateWithOptions and it doesn't help:

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:

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:)

So, my question is: How to start gui process and bring it to front without hacks?

PS: I know that 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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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