简体   繁体   中英

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

I would like to enable my GUI users (GI users?) to switch to a known, friendly application directly, eg 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.

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);
}

If the applications really are friendly, ie 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:

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:

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

Searching for WinActivate led to a AutoHotkey forum post which links to WinAPI's GetForegroundWindow and SetForegroundWindow .

BOOL WINAPI SetForegroundWindow(
   _In_  HWND hWnd
);

However, this is not a true solution yet as it

  • requires a window handle (how to get it by window title?)
  • has limited permissions (process ownership trickery neccessary: here and here )

The latter link is quite elaborate, but the author seems to have given up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM