0

How can I switch to another running application in Windows 7 and C++ when I know its process id?

I only have the process id. There might be several applications with the same name so using the window title does not work. I also do not have a reliable HWND to use.

I want the application to be active, visible and ready for input just as if I switched to it using alt-tab.

HardCoder
  • 3,026
  • 6
  • 32
  • 52
  • have you tried the obvious `c++ windows switch to application` search? – Karoly Horvath Apr 07 '14 at 16:26
  • 1
    Just enumerate all top level windows until you find one belonging to the PID with the `WS_EX_APPWINDOW` style set. Bring that window to the front of the z-order and give it input focus. – Captain Obvlious Apr 07 '14 at 16:31
  • That does not really work reliably because not every Application has the WS_EX_APPWINDOW style set. – HardCoder Apr 07 '14 at 16:47
  • If the app appears on the task bar or in the task-switch window it has the `WS_EX_APPWINDOW` style. If not choose a criteria that gets you as close as possible. – Captain Obvlious Apr 07 '14 at 16:51
  • Out of 6 Apps I tried that are on the taskbar only 1 had the WS_EX_APPWINDOW style set. And simply choosing criterias that might not work reliably sounds sloppy. – HardCoder Apr 07 '14 at 17:08

1 Answers1

0

Try

HWND hNewWindow = FindWindow(...); // get window handle by title etc.
if (hNewWindow)
{
    DWORD hCurrentWindowThread = GetWindowThreadProcessId( hWndCurrentWindow, NULL );
    DWORD hNewWindowThread = GetWindowThreadProcessId( hNewWindow, NULL);
    AttachThreadInput( hCurrentWindowThread, hNewWindowThread, TRUE );
    SetForegroundWindow(hNewWindow);
    AttachThreadInput( hCurrentWindowThread, hNewWindowThread, FALSE );
}

SetForegroundWindow is doing the magic you want here. It has limitations outlined here SetforegroundWindow() API

Solution from here.

David Zech
  • 745
  • 3
  • 14