I am launching a process from my application using CreateProcess API and I want to bring the window of the new process to top. Is there a way to do it? Do we have any flag or something like that with CreateProcess?
-
http://stackoverflow.com/questions/916259/win32-bring-a-window-to-top – Seb Holzapfel Jul 27 '11 at 08:20
-
You mean just showing the window, or actually brining it on top? – Ajay Jul 28 '11 at 15:53
-
There is a useful answer in this duplicate: http://stackoverflow.com/questions/25034867/how-to-make-createprocess-open-new-process-in-focus-and-not-in-background A simple `TranslateMessage` call makes it work as expected. – Kaz Jul 01 '16 at 00:58
2 Answers
You can try to use the STARTUPINFO structure which is passed in with CreateProcess and set SW_SHOW. I'm not sure this will help bring the focus to the top though. If that doesn't work then try the following.
First off, do not use FindWindow(), it is unnecessarily unreliable since it only works via the window name and class name. Instead, from your CreateProcess() call you should read lpProcessInformation and grab the dwProcessId. Then call EnumWindows() and have your callback look something like this:
BOOL CALLBACK EnumWindowsProc( HWND hwnd, LPARAM lParam ) {
DWORD dwPID;
GetWindowThreadProcessId( hwnd, &dwPID );
if( dwPID == lParam ) {
SetWindowPos( hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
// Or just SetFocus( hwnd );
return FALSE;
}
return TRUE;
}
When calling EnumWindows() you will need to pass in the PID you grabbed earlier as the lParam like so:
EnumWindows( EnumWindowsProc, ( LPARAM )( PI -> dwProcessId ) );

- 24,123
- 12
- 63
- 96
You need the window handle of the application you launched. If you don't have it, you could use the FindWindowA API call.
Then use the SetFocus API call with the window handle as parameter.
Related links:
http://www.andreavb.com/tip020001.html
http://msdn.microsoft.com/en-us/library/aa697422%28v=vs.71%29.aspx

- 1,423
- 3
- 16
- 32
-
2But definitely don't use `FindWindowA`. The ANSI variant went out of style with Windows 98. Not sure where you got this advice. Any application written in the past 15 years should be using the Unicode versions of these functions. `FindWindowW` is the function you're looking for, or better yet, `FindWindow`. Did you notice the ancient trifle you'd dug up on MSDN? It's in a category titled "porting 16-bit code to 32-bit Windows". – Cody Gray - on strike Jul 27 '11 at 09:02
-
+1 for Jeroen. I wanted to avoid call to FindWindow. I used the suggestion from Mike. – Rahul Jul 28 '11 at 06:08