[Interest] Preventing Multiple Instances of EXE

Shantanu Tushar shaan7in at gmail.com
Sun Apr 24 11:56:27 CEST 2016


The following approach has worked quite well (I'm using it in sostronk.com's
desktop app):

// H
class UniqueApp : public QObject
{
    Q_OBJECT
public:
    explicit UniqueApp(QObject *parent = 0);
    static bool anotherInstanceRunning();
    void monitor();

signals:
    void anotherInstance();
};


// CPP

static const int TIMEOUT = 100;

bool UniqueApp::anotherInstanceRunning()
{
    QLocalSocket c;
    c.connectToServer(QString("%1").arg(qApp->applicationName()));
    qDebug() << "Trying to connect to existing instance of " <<
c.serverName();
    return c.waitForConnected(TIMEOUT);
}

void UniqueApp::monitor()
{
    auto s = new QLocalServer(this);
    s->listen(qApp->applicationName());
    connect(s, &QLocalServer::newConnection, this,
&UniqueApp::anotherInstance);
}


On Sat, Apr 23, 2016 at 12:37 AM, Jason Kretzer <Jason at gocodigo.com> wrote:

> Everyone,
>
> Anyone know how to prevent multiple instances of an exe to be started?
> So, I start bob.exe.  I then I try to double click and start bob.exe again
> while the first is still running and a second instance does not start (or
> at least shuts itself down or does anything other than start another
> instance).
>
> Is there a Qt/C++ on Windows way to do that?
>
> //------------------------------//
>    Jason R. Kretzer
>    Lead Application Developer
>    Jason at gocodigo.com
> //------------------------------//
>
> “quidquid latine dictum sit altum videtur"
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/interest
>
>


-- 
Shantanu Tushar    (UTC +0530)
shantanu.io
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160424/cd4aaa15/attachment.html>


More information about the Interest mailing list