diff --git a/dev/WebView2/WebView2.cpp b/dev/WebView2/WebView2.cpp index 1fa99d6fbf..8c30b788c9 100644 --- a/dev/WebView2/WebView2.cpp +++ b/dev/WebView2/WebView2.cpp @@ -1255,14 +1255,28 @@ void WebView2::FireCoreWebView2Initialized(winrt::hresult exception) m_coreWebView2InitializedEventSource(*this, *eventArgs); } -void WebView2::HandleGotFocus(const winrt::Windows::Foundation::IInspectable&, const winrt::RoutedEventArgs&) noexcept +void WebView2::HandleGotFocus(const winrt::Windows::Foundation::IInspectable&, const winrt::RoutedEventArgs&) { if (m_coreWebView && m_xamlFocusChangeInfo.m_isPending) { - // In current CoreWebView2 API, MoveFocus is not expected to fail, so set m_webHasFocus here rather than - // in asynchronous (MOJO/cross-proc) CoreWebView2 GotFocus event. - m_webHasFocus = true; - m_coreWebViewController.MoveFocus(m_xamlFocusChangeInfo.m_storedMoveFocusReason); + try + { + m_coreWebViewController.MoveFocus(m_xamlFocusChangeInfo.m_storedMoveFocusReason); + m_webHasFocus = true; + } + catch (winrt::hresult_error e) + { + // Occasionally, a request to restore the minimized window does not complete. This triggers + // FocusManager to set Xaml Focus to WV2 and consequently into CWV2 MoveFocus() call above, + // which in turn will attempt ::SetFocus() on InputHWND, and that will fail with E_INVALIDARG + // since that HWND remains minimized. Work around by ignoring this error here. Since the app + // is minimized, focus state is not relevant - the next (successful) attempt to restrore the app + // will set focus into WV2/CWV2 correctly. + if (e.code().value != E_INVALIDARG) + { + throw; + } + } m_xamlFocusChangeInfo.m_isPending = false; } } diff --git a/dev/WebView2/WebView2.h b/dev/WebView2/WebView2.h index 905c40b6e4..dfa4a69d21 100644 --- a/dev/WebView2/WebView2.h +++ b/dev/WebView2/WebView2.h @@ -146,7 +146,7 @@ class WebView2 : void HandlePointerCaptureLost(const winrt::Windows::Foundation::IInspectable&, const winrt::PointerRoutedEventArgs& args); void HandleKeyDown(const winrt::Windows::Foundation::IInspectable&, const winrt::KeyRoutedEventArgs& e); void HandleGettingFocus(const winrt::Windows::Foundation::IInspectable&, const winrt::GettingFocusEventArgs& args) noexcept; - void HandleGotFocus(const winrt::Windows::Foundation::IInspectable&, const winrt::RoutedEventArgs&) noexcept; + void HandleGotFocus(const winrt::Windows::Foundation::IInspectable&, const winrt::RoutedEventArgs&); void HandleAcceleratorKeyActivated(const winrt::Windows::UI::Core::CoreDispatcher&, const winrt::AcceleratorKeyEventArgs& args) noexcept; void HandleXamlRootChanged(); void HandleSizeChanged(const winrt::IInspectable& /*sender*/, const winrt::SizeChangedEventArgs& args);