private static bool TrySetForegroundWindow()

in src/Microsoft.VisualStudio.Extensibility.Testing.Xunit.Shared/InProcess/VisualStudio_InProc.cs [183:224]


        private static bool TrySetForegroundWindow(HWND window)
        {
            var activeWindow = PInvoke.GetLastActivePopup(window);
            activeWindow = PInvoke.IsWindowVisible(activeWindow) ? activeWindow : window;
            PInvoke.SwitchToThisWindow(activeWindow, true);

            if (!PInvoke.SetForegroundWindow(activeWindow))
            {
                if (!PInvoke.AllocConsole())
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                try
                {
                    var consoleWindow = PInvoke.GetConsoleWindow();
                    if (consoleWindow == IntPtr.Zero)
                    {
                        throw new InvalidOperationException("Failed to obtain the console window.");
                    }

                    if (!PInvoke.SetWindowPos(consoleWindow, hWndInsertAfter: (HWND)0, 0, 0, 0, 0, SET_WINDOW_POS_FLAGS.SWP_NOZORDER))
                    {
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                    }
                }
                finally
                {
                    if (!PInvoke.FreeConsole())
                    {
                        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                    }
                }

                if (!PInvoke.SetForegroundWindow(activeWindow))
                {
                    return false;
                }
            }

            return true;
        }