Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch to another application on Windows (using C++, Qt)?

Tags:

c++

windows

qt

I would like to enable my GUI users (GI users?) to switch to a known, friendly application directly, e.g. by keyboard shortcut. Ideally, my application would request the OS / Windows to show application by name or main window title string "XYZ".

The manual path of action would be ALT+TAB to open the Windows Task Switcher and then locating and navigating to the desired application icon to finally bring it into the foreground of active program windows. Alternatively, navigation via the Task Bar.

AutoHotkey has a function WinActivate that does what I want to achieve.

like image 897
handle Avatar asked Feb 17 '23 00:02

handle


2 Answers

The following code works here without problem on Windows 7:

#include <windows.h>

[...]

// find window handle using the window title
HWND hWnd = ::FindWindow(NULL, L"Window Title");
if (hWnd) {
    // move to foreground
    ::SetForegroundWindow(hWnd);
}
like image 89
cloose Avatar answered Feb 27 '23 09:02

cloose


If the applications really are friendly, i.e. both are under one's control, an easier solution might make use of a communication socket or shared library that allows to have the other application bring up itself.

Which seems to be tricky enough -- delay the call:

QTimer::singleShot( 2000,
                    this,
                    SLOT( toForeground() )
                    );

to this slot:

void MainWindow::toForeground()
{
    qDebug() << SetForegroundWindow( this->winId() );
}

This will show the Task Bar and highlight the application icon shortly. It does not switch to the application.

Qt's own activateWindow() results in a more persistent blinking task bar icon but does not raise the application.

This has been tried before:

  • Bring window to front -> raise(),show(),activateWindow() don’t work
  • Qt Need to bring Qt application to foreground called from win32 application
  • http://qt-project.org/forums/viewthread/1971

The latter suggests:

showNormal();
raise();
activateWindow(); 

but that does not work for me on Windows 7 64 bit with Qt 4.8.1 and MSVC++ 2010.

Here is code that I think is also mentioned in the other questions:

  • http://qt-project.org/forums/viewthread/1971/#9038

The author writes

It always brings the window to the front, but the focus is somewhere in the system :-( In some other app…

This I can confirm.


Edit: Windows' behaviour can (shouldn't!?) be changed globally via Registry: https://stackoverflow.com/a/6087923/1619432 points to http://qt-project.org/faq/answer/qwidget_activatewindow_-_behavior_under_windows
like image 31
handle Avatar answered Feb 27 '23 11:02

handle