SingleApplication/examples/windows_raise_widget/main.cpp

60 lines
1.2 KiB
C++
Raw Normal View History

2023-03-13 15:36:59 +08:00
#include <QWidget>
#include "singleapplication.h"
#ifdef Q_OS_WINDOWS
#include <Windows.h>
#endif
void raiseWidget(QWidget* widget);
2023-03-13 15:36:59 +08:00
int main(int argc, char *argv[]) {
#ifdef Q_OS_WINDOWS
2023-03-13 15:36:59 +08:00
SingleApplication app(argc, argv, true);
if (app.isSecondary()) {
AllowSetForegroundWindow( DWORD( app.primaryPid() ) );
app.sendMessage("RAISE_WIDGET");
2023-03-13 15:36:59 +08:00
return 0;
}
#else
SingleApplication app(argc, argv);
#endif
2023-03-13 15:36:59 +08:00
QWidget* widget = new QWidget;
#ifdef Q_OS_WINDOWS
2023-03-13 15:36:59 +08:00
QObject::connect(&app, &SingleApplication::receivedMessage,
widget, [widget] () { raiseWidget(widget); } );
#else
QObject::connect(&app, &SingleApplication::instanceStarted,
widget, [widget] () { raiseWidget(widget); } );
#endif
2023-03-13 15:36:59 +08:00
widget->show();
return app.exec();
}
void raiseWidget(QWidget* widget) {
#ifdef Q_OS_WINDOWS
2023-03-13 15:36:59 +08:00
HWND hwnd = (HWND)widget->winId();
// check if widget is minimized to Windows task bar
2023-03-13 15:36:59 +08:00
if (::IsIconic(hwnd)) {
::ShowWindow(hwnd, SW_RESTORE);
}
::SetForegroundWindow(hwnd);
#else
widget->show();
widget->raise();
widget->activateWindow();
#endif
2023-03-13 15:36:59 +08:00
}