In my GUI application, I’m using the C# Process class to spawn external processes which may launch windows. The subprocess windows may be displayed via third-party API calls, so it’s not always possible to get the window handle. Is there any way to ensure that the subprocess’s windows are displayed in front of the main application window?
In my GUI application, I’m using the C# Process class to spawn external processes
Share
The usual method is:
1 . Get Process class instance returned by Process.Start()
2 . Query Process.MainWindowHandle
3 . Call unmanaged Win32 API function “ShowWindow” or “SwitchToThisWindow”
The trick to your question is that “sub-process windows may be displayed via third-party API calls”. In that case you will need Get the Window Handle of the spawned exe and Enum Child Windows. Once you have the Handles for the forms that are shown after API calls you can use the BringWindowToTop API.
I put together a small test using How To Enumerate Windows Using the WIN32 API as inspiration. Create a Windows application with 1 form and 2 buttons:
The 3rdPartyAppExample is a Winform App with 2 forms. I reference this application and call Form1’s Public method to show Form2:
Optionally you may wish to check the Windows Caption:
The other solution (that isn’t very stable) is discussed here:
http://www.shloemi.com/2012/09/solved-setforegroundwindow-win32-api-not-always-works/
The trick is to make windows ‘think’ that our process and the target window (hwnd) are related by attaching the threads (using AttachThreadInput API).
Regarding the
myTopForm.TopMost = trueanswer, that will not work for external applications.