I'm trying to create a single instance Qt application and I'm at the point this works, but now I want to focus the already started instance when a second is started. QWidget::find(g_hWnd) should return the widget but it fails and crashes on w->show();
Any thoughts?
#pragma data_seg("Shared")
HWND g_hWnd = NULL;
#pragma data_seg()
#pragma comment(linker,"/section:Shared,rws")
int main(int argc, char *argv[])
{
if (g_hWnd)
{
QWidget* w = QWidget::find(g_hWnd);
w->show();
return 0;
}
else
{
QApplication a(argc, argv);
mainWindow w;
w.show();
g_hWnd = a.topLevelWidgets().at(0)->winId(); //or w.winId()?
return a.exec();
}
}
edit: I now see Trolltech released the QtSingleApplication class under LGPL.
You should use the qtsingleapplication API
edit- It's a separate download see here for both LGPL and Commercial editions
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QMessageBox>
#include <QSharedMemory>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
QSharedMemory shared("61BB200D-3579-453e-9044-");
if(shared.create(512,QSharedMemory::ReadWrite)==true)
{
QMessageBox msgBox;
msgBox.setText("I am first.");
msgBox.exec();
}
else
{
QMessageBox msgBox;
msgBox.setText("i am already running.");
msgBox.exec();
exit(0);
}
//shared.AlreadyExists()
w.show();
return a.exec();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With