当前位置:首页 » 《随便一记》 » 正文

Qt SingleApplication实现_yonggandess的博客

27 人参与  2022年05月09日 18:14  分类 : 《随便一记》  评论

点击全文阅读


#pragma once
#include <QObject>
#include <QApplication>
#include <QtNetwork/QLocalServer>
#include <QWidget>

class SingleApp : public QApplication
{
	Q_OBJECT
public:
	explicit SingleApp(int &argc, char **argv);

	bool isRunning();
	QWidget *w;

private slots:
	void newLocalConnection();

private:
	void initLocalConnection();
	void newLocalServer();
	void activateWindow();

	bool m_isRunning;
	QLocalServer *m_localServer;
	QString m_serverName;
};

#include "SingleApp.h"
#include <QtNetwork/QLocalSocket>
#include <QFileInfo>

#define TIME_OUT                (500)    // 500ms
SingleApp::SingleApp(int &argc, char **argv)
	: QApplication(argc, argv)
	, w(nullptr)
	, m_isRunning(false)
	, m_localServer(nullptr)
{
	m_serverName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
	m_serverName += "appName";
	initLocalConnection();
}
bool SingleApp::isRunning()
{
	return m_isRunning;
}

void SingleApp::newLocalConnection()
{
	QLocalSocket *socket = m_localServer->nextPendingConnection();
	if (socket) {
		socket->waitForReadyRead(2 * TIME_OUT);
		delete socket;
		activateWindow();
	}
}

void SingleApp::initLocalConnection()
{
	m_isRunning = false;
	QLocalSocket socket;
	socket.connectToServer(m_serverName);
	if (socket.waitForConnected(TIME_OUT)) {
		fprintf(stderr, "%s already running.\n",
			m_serverName.toLocal8Bit().constData());
		m_isRunning = true;
		return;
	}
	newLocalServer();
}

void SingleApp::newLocalServer()
{
	m_localServer = new QLocalServer(this);
	connect(m_localServer, SIGNAL(newConnection()), this, SLOT(newLocalConnection()));
	if (!m_localServer->listen(m_serverName)) {
		if (m_localServer->serverError() == QAbstractSocket::AddressInUseError) {
			QLocalServer::removeServer(m_serverName);
			m_localServer->listen(m_serverName);
		}
	}
}

void SingleApp::activateWindow()
{
	if (w) {
		w->show();
		w->raise();
		w->activateWindow();
	}
}


点击全文阅读


本文链接:http://zhangshiyu.com/post/39805.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1