LocalThread::LocalThread(quintptr socketDescriptor, const QString& name, QObject* parent) : QThread(parent){ this->socketDescriptor = socketDescriptor; this->name = name;}LocalThread::~LocalThread(){ if (!isRunning()) return; stop(); wait();}void LocalThread::stop(){ QMutexLocker locker( &m_stopMutex ); m_stopped = true;}void LocalThread::run(){ m_stopMutex.lock(); m_stopped = false; m_stopMutex.unlock(); QLocalSocket socket; if(!socket.setSocketDescriptor(socketDescriptor) || socket.state() != QLocalSocket::ConnectedState) return; // send app_id to client if(!writeMessage(&socket, name)) return; // wait to messages from client while(socket.state() == QLocalSocket::ConnectedState && !m_stopped) { if(socket.waitForReadyRead(1000)) {// ... } }}
#include <QtCore/QObject>#include <QtCore/QString>#include <QtGui/QApplication>#include "mainwindow.h"#include "singleapplication.h"#ifdef Q_WS_WIN#include <QtCore/QLibrary>typedef int (*ASFW_Func) (qint32);#endifint main(int argc, char* argv[]){ QApplication app(argc, argv); QStringList args = app.arguments(); args.removeFirst(); QString message = args.join(" ");#ifdef Q_WS_WIN ASFW_Func AllowSetForegroundWindow = (ASFW_Func) QLibrary::resolve("user32", "AllowSetForegroundWindow"); if (AllowSetForegroundWindow) AllowSetForegroundWindow(-1);#endif SingleApplication instance("LoaderExample"); if(instance.isRunning()) { if(instance.sendMessage(message)) return 0; } MainWindow mw; mw.handleMessage(message); mw.show(); QObject::connect(&instance, SIGNAL(messageReceived(const QString&)), &mw, SLOT(handleMessage(const QString&))); return app.exec();}
#ifdef Q_WS_WIN #include <QtCore/QLibrary> #include <windows.h> typedef BOOL (*ASFW_Func) (DWORD);#endif
#ifdef Q_WS_WIN ASFW_Func asfw = (ASFW_Func) QLibrary::resolve("user32", "AllowSetForegroundWindow"); if (asfw) asfw(-1);#endif