📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)
| 166行目: | 166行目: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<br> | <br> | ||
<syntaxhighlight lang="c++"> | |||
#include <QLocalServer> | |||
#include <QLocalSocket> | |||
#include <QSharedMemory> | |||
#include <QDataStream> | |||
class SingletonInstance : public QObject | |||
{ | |||
Q_OBJECT | |||
private: | |||
QString m_key; | |||
QSharedMemory m_sharedMemory; | |||
QLocalServer *m_pServer; | |||
public: | |||
SingletonInstance(const QString &key) : m_key(key), m_sharedMemory(key), m_pServer(new QLocalServer(this)) | |||
{ | |||
connect(m_pServer, &QLocalServer::newConnection, this, &SingletonInstance::handleConnection); | |||
} | |||
bool tryToRun() | |||
{ | |||
if (m_sharedMemory.attach()) { | |||
return false; // 別のインスタンスが既に実行中 | |||
} | |||
if (!m_sharedMemory.create(1)) { | |||
return false; // 共有メモリの作成に失敗 | |||
} | |||
if (!m_pServer->listen(m_key)) { | |||
return false; // サーバの起動に失敗 | |||
} | |||
return true; | |||
} | |||
public slots: | |||
void sendMessage(const QString &message) | |||
{ | |||
QLocalSocket socket; | |||
socket.connectToServer(m_key); | |||
if (socket.waitForConnected(1000)) { | |||
QByteArray block; | |||
QDataStream out(&block, QIODevice::WriteOnly); | |||
out << message; | |||
socket.write(block); | |||
socket.flush(); | |||
socket.waitForBytesWritten(); | |||
socket.disconnectFromServer(); | |||
} | |||
} | |||
signals: | |||
void messageReceived(const QString &message); | |||
private slots: | |||
void handleConnection() | |||
{ | |||
QLocalSocket *pSocket = m_pServer->nextPendingConnection(); | |||
if (pSocket) { | |||
connect(pSocket, &QLocalSocket::readyRead, this, [this, pSocket]() { | |||
QDataStream in(pSocket); | |||
QString message; | |||
in >> message; | |||
emit messageReceived(message); | |||
pSocket->deleteLater(); | |||
}); | |||
} | |||
} | |||
}; | |||
</syntaxhighlight> | |||
<br> | |||
<syntaxhighlight lang="c++"> | |||
// main.cppファイル | |||
#include <QApplication> | |||
#include <QMessageBox> | |||
#include "mainwindow.h" | |||
#include "SingletonInstance.h" | |||
int main(int argc, char *argv[]) | |||
{ | |||
QApplication app(argc, argv); | |||
SingletonInstance instance("/tmp/MyAppServer"); | |||
if (!instance.tryToRun()) { | |||
// 別のインスタンスが既に実行中の場合、メッセージを送信して終了 | |||
QMessageBox::warning(nullptr, "多重起動エラー", "多重起動を検出しました", QMessageBox::Ok); | |||
instance.sendMessage("新しいインスタンスが起動を試みました"); | |||
return -1; | |||
} | |||
// 最初のインスタンスの場合、メインウィンドウをセットアップしてアプリケーションを実行 | |||
QObject::connect(&instance, &SingletonInstance::messageReceived, [](const QString &message) { | |||
qDebug() << "受信したメッセージ: " << message; | |||
// ここでメッセージを処理する | |||
// 例: ウインドウを前面に表示する等 | |||
}); | |||
// メインウインドウのセットアップをここに記述 | |||
MainWindow mainWindow; | |||
mainWindow.show(); | |||
return app.exec(); | |||
} | |||
</syntaxhighlight> | |||
<br><br> | <br><br> | ||