Using SetForegroundWindow to activate another process’ window

Thanks to the Dr. Dobb’s Portal article which revealed the secret of bringing another process’ window using SetForegroundWindow API.

Sometimes, you may launch another process using CreateProcess or ShellExecute API. But the focus may remain in the current process instead of the new process that you just spawned. You might see the new process’ window button blinking in the taskbar wanting the user to activate it.

Here is the code that will let you to activate another process’ window.

HWND hWndCurrentWindow = GetForegroundWindow();
CString strTitleNewWindow;
HWND hNewWindow = FindWindow(NULL, strTitle);
if (hNewWindow)
	DWORD hCurrentWindowThread = GetWindowThreadProcessId( hWndCurrentWindow, NULL );
	DWORD hNewWindowThread = GetWindowThreadProcessId( hNewWindow, NULL);
	AttachThreadInput( hCurrentWindowThread, hNewWindowThread, TRUE );
	AttachThreadInput( hCurrentWindowThread, hNewWindowThread, FALSE );

Leave a Reply

Your email address will not be published. Required fields are marked *