From cf1cfb8ea92be7843db07dac8dcde42b50d510f6 Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Mon, 1 Nov 2021 09:45:26 -0700 Subject: [PATCH] Retry SetForegroundWindow with DTE.MainWindow See dotnet/roslyn#57314 --- .../InProcess/VisualStudio_InProc.cs | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.VisualStudio.Extensibility.Testing.Xunit.Shared/InProcess/VisualStudio_InProc.cs b/src/Microsoft.VisualStudio.Extensibility.Testing.Xunit.Shared/InProcess/VisualStudio_InProc.cs index 89a37bf..3758573 100644 --- a/src/Microsoft.VisualStudio.Extensibility.Testing.Xunit.Shared/InProcess/VisualStudio_InProc.cs +++ b/src/Microsoft.VisualStudio.Extensibility.Testing.Xunit.Shared/InProcess/VisualStudio_InProc.cs @@ -61,14 +61,20 @@ public void ActivateMainWindow() var activeVisualStudioWindow = (IntPtr)dte.ActiveWindow.HWnd; Debug.WriteLine($"DTE.ActiveWindow.HWnd = {activeVisualStudioWindow}"); - - if (activeVisualStudioWindow == IntPtr.Zero) + if (activeVisualStudioWindow != IntPtr.Zero) { - activeVisualStudioWindow = (IntPtr)dte.MainWindow.HWnd; - Debug.WriteLine($"DTE.MainWindow.HWnd = {activeVisualStudioWindow}"); + if (TrySetForegroundWindow(activeVisualStudioWindow)) + { + return; + } } - SetForegroundWindow(activeVisualStudioWindow); + activeVisualStudioWindow = (IntPtr)dte.MainWindow.HWnd; + Debug.WriteLine($"DTE.MainWindow.HWnd = {activeVisualStudioWindow}"); + if (!TrySetForegroundWindow(activeVisualStudioWindow)) + { + throw new InvalidOperationException("Failed to set the foreground window."); + } }); } @@ -119,7 +125,7 @@ public void Quit() }); } - private static void SetForegroundWindow(IntPtr window) + private static bool TrySetForegroundWindow(IntPtr window) { var activeWindow = NativeMethods.GetLastActivePopup(window); activeWindow = NativeMethods.IsWindowVisible(activeWindow) ? activeWindow : window; @@ -155,9 +161,11 @@ private static void SetForegroundWindow(IntPtr window) if (!NativeMethods.SetForegroundWindow(activeWindow)) { - throw new InvalidOperationException("Failed to set the foreground window."); + return false; } } + + return true; } } }