2022-04-06 18:28:38 +08:00
|
|
|
# Windows Specifics
|
2017-10-02 19:17:41 +08:00
|
|
|
|
2022-04-06 05:04:31 +08:00
|
|
|
## Setting the foreground window
|
2017-10-02 19:17:41 +08:00
|
|
|
|
|
|
|
In the `instanceStarted()` example in the `README` we demonstrated how an
|
|
|
|
application can bring it's primary instance window whenever a second copy
|
|
|
|
of the application is started.
|
|
|
|
|
|
|
|
On Windows the ability to bring the application windows to the foreground is
|
2022-04-06 05:04:31 +08:00
|
|
|
restricted, see [AllowSetForegroundWindow()][https://msdn.microsoft.com/en-us/library/windows/desktop/ms632668.aspx] for more
|
2017-10-02 19:17:41 +08:00
|
|
|
details.
|
|
|
|
|
|
|
|
The background process (the primary instance) can bring its windows to the
|
|
|
|
foreground if it is allowed by the current foreground process (the secondary
|
|
|
|
instance). To bypass this `SingleApplication` must be initialized with the
|
2023-03-13 15:36:59 +08:00
|
|
|
`allowSecondary` parameter set to `true` .
|
|
|
|
|
|
|
|
If the widget is minimized to Windows task bar, `QWidget::raise()` or
|
|
|
|
`QWidget::show()` can not bring it to the front, you have to use Windows API
|
|
|
|
`ShowWindow()` .
|
2017-10-02 19:17:41 +08:00
|
|
|
|
2023-03-13 15:36:59 +08:00
|
|
|
Here is an example, you can find this project in the example directory:
|
2017-10-02 19:17:41 +08:00
|
|
|
|
|
|
|
```cpp
|
2023-03-13 15:36:59 +08:00
|
|
|
SingleApplication app(argc, argv, true);
|
|
|
|
if ( app.isSecondary() ) {
|
2017-10-02 19:17:41 +08:00
|
|
|
// This API requires LIBS += User32.lib to be added to the project
|
2019-02-25 23:16:39 +08:00
|
|
|
AllowSetForegroundWindow( DWORD( app.primaryPid() ) );
|
2017-10-02 19:17:41 +08:00
|
|
|
|
2023-03-13 15:36:59 +08:00
|
|
|
objApp.sendMessage("SHOW_WINDOW");
|
|
|
|
|
|
|
|
return 0;
|
2017-10-02 19:17:41 +08:00
|
|
|
}
|
2023-03-13 15:36:59 +08:00
|
|
|
|
|
|
|
QWidget* widget = new QWidget;
|
|
|
|
|
|
|
|
QObject::connect(&app, &SingleApplication::receivedMessage,
|
|
|
|
widget, [widget] () { RaiseWidget(widget); } );
|
2017-10-02 19:17:41 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
```cpp
|
2023-03-13 15:36:59 +08:00
|
|
|
void RaiseWidget(QWidget* widget) {
|
|
|
|
|
|
|
|
HWND hwnd = (HWND)widget->winId();
|
|
|
|
|
|
|
|
// check if widget is minimized
|
|
|
|
if (::IsIconic(hwnd)) {
|
|
|
|
::ShowWindow(hwnd, SW_RESTORE);
|
|
|
|
}
|
|
|
|
|
|
|
|
::SetForegroundWindow(hwnd);
|
2017-10-02 19:17:41 +08:00
|
|
|
}
|
|
|
|
```
|