MicrosoftEdge / WebView2Feedback

Feedback and discussions about Microsoft Edge WebView2
https://aka.ms/webview2
452 stars 55 forks source link

Displaying WebView2 from an unmanaged (C++) application throws exception #2318

Closed dh0well closed 2 years ago

dh0well commented 2 years ago

Description

When trying to display a WPF Window which contains a WebView2 control from a C++ (MFC-based) application, the EnsureCoreWebView2Async() method will throw a System.InvalidOperationException. (There are two different types of exceptions depending on which WebView2 version is in use, see Repo Steps below.)

What might cause this? Perhaps there is some limitation I am unaware of, or maybe there is a required step absent in the sample application I am using: https://github.com/TechSmith/WebViewIssue

CoreWebView2 members can only be accessed from the UI thread.
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{4D00C0D1-9434-4EB6-8078-8697A560334F}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
   at Microsoft.Web.WebView2.Core.CoreWebView2Controller.add_AcceleratorKeyPressed(EventHandler`1 value)
   at Microsoft.Web.WebView2.Wpf.WebView2.<>c__DisplayClass27_0.<<EnsureCoreWebView2Async>g__Init|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at View.NET.WebViewControl.<InitializeWebView>d__8.MoveNext() in C:\src\WebViewIssue\View.NET\WebViewControl.xaml.cs:line 64
----- Visual Studio Output window messages ----- ``` Exception thrown at 0x00007FFA61864F69 (KernelBase.dll) in App.MDI.exe: WinRT originate error - 0x80040155 : 'Failed to find proxy registration for IID: {4D00C0D1-9434-4EB6-8078-8697A560334F}.'. onecore\com\combase\winrt\error\restrictederror.cpp(1016)\combase.dll!00007FFA635CBEE3: (caller: 00007FFA635D5BC9) ReturnHr(1) tid(9654) 8007007E The specified module could not be found. Exception thrown at 0x00007FFA61864F69 (KernelBase.dll) in App.MDI.exe: 0x40080202: WinRT transform error (parameters: 0x0000000080040155, 0x0000000080004002, 0x000000000000001D, 0x000000FC164FDCB0). Exception thrown at 0x00007FFA61864F69 (KernelBase.dll) in App.MDI.exe: WinRT originate error - 0x80040155 : 'Failed to find proxy registration for IID: {4D00C0D1-9434-4EB6-8078-8697A560334F}.'. onecore\com\combase\winrt\error\restrictederror.cpp(1016)\combase.dll!00007FFA635CBEE3: (caller: 00007FFA635D5BC9) ReturnHr(2) tid(9654) 8007007E The specified module could not be found. Exception thrown at 0x00007FFA61864F69 (KernelBase.dll) in App.MDI.exe: 0x40080202: WinRT transform error (parameters: 0x0000000080040155, 0x0000000080004002, 0x000000000000001D, 0x000000FC164FD3D0). Exception thrown: 'System.InvalidCastException' in Microsoft.Web.WebView2.Core.dll Exception thrown: 'System.InvalidOperationException' in Microsoft.Web.WebView2.Core.dll Exception thrown: 'System.InvalidOperationException' in Microsoft.Web.WebView2.Wpf.dll Exception thrown: 'System.InvalidOperationException' in mscorlib.dll ```

Version SDK: 1.0.1020.30 Framework: MFC, WPF OS: Win10 21H2

Repro Steps

  1. Clone the sample application repo which demonstrates this issue: https://github.com/TechSmith/WebViewIssue
  2. Build the Solution
  3. Run App.NET
    • Click the [Open WebView] button
    • Verify that it shows the window with the WebView2 control sans-drama
  4. Run App.MDI
----- Call stack at the point where EnsureCoreWebView2Async() is called: ----- ``` > View.NET.dll!View.NET.WebViewControl.InitializeWebView() Line 64 C# Symbols loaded. View.NET.dll!View.NET.WebViewControl.OnSourcePropertyChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) Line 36 C# Symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.FrameworkElement.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e) Unknown No symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.NotifyPropertyChange(System.Windows.DependencyPropertyChangedEventArgs args) Unknown No symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.UpdateEffectiveValue(System.Windows.EntryIndex entryIndex, System.Windows.DependencyProperty dp, System.Windows.PropertyMetadata metadata, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType) Unknown No symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.InvalidateProperty(System.Windows.DependencyProperty dp, bool preserveCurrentValue) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.Invalidate(bool isASubPropertyChange) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.TransferValue(object newValue, bool isASubPropertyChange) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.Activate(object item) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.AttachToContext(System.Windows.Data.BindingExpression.AttachAttempt attempt) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(bool lastChance) Unknown No symbols loaded. PresentationFramework.dll!MS.Internal.Data.DataBindEngine.Task.Run(bool lastChance) Unknown No symbols loaded. PresentationFramework.dll!MS.Internal.Data.DataBindEngine.Run(object arg) Unknown No symbols loaded. PresentationCore.dll!System.Windows.ContextLayoutManager.fireLayoutUpdateEvent() Unknown No symbols loaded. PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayout() Unknown No symbols loaded. PresentationCore.dll!System.Windows.Interop.HwndSource.SetLayoutSize() Unknown No symbols loaded. PresentationCore.dll!System.Windows.Interop.HwndSource.RootVisualInternal.set(System.Windows.Media.Visual value) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.SetRootVisual() Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.SetRootVisualAndUpdateSTC() Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.SetupInitialState(double requestedTop, double requestedLeft, double requestedWidth, double requestedHeight) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.CreateSourceWindow(bool duringShow) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.ShowHelper(object booleanBox) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.ShowDialog() Unknown No symbols loaded. View.NET.dll!View.NET.WebViewPresenter.ShowModal(System.IntPtr hWndParent) Line 29 C# Symbols loaded. Interop.dll!Interop::Show::Go(HWND__* hWndParent) Line 28 C++ Symbols loaded. Interop.dll!Interop::ShowWebView::Go(HWND__* hWndParent) Line 9 C++ Symbols loaded. [Native to Managed Transition] Annotated Frame App.MDI.exe!CAppMDIApp::OnFileOpenwebview() Line 78 C++ Symbols loaded. mfc140ud.dll!_AfxDispatchCmdMsg(CCmdTarget * pTarget, unsigned int nID, int nCode, void(CCmdTarget::*)() pfn, void * pExtra, unsigned __int64 nSig, AFX_CMDHANDLERINFO * pHandlerInfo) Line 78 C++ Symbols loaded. mfc140ud.dll!CCmdTarget::OnCmdMsg(unsigned int nID, int nCode, void * pExtra, AFX_CMDHANDLERINFO * pHandlerInfo) Line 372 C++ Symbols loaded. mfc140ud.dll!CFrameWnd::OnCmdMsg(unsigned int nID, int nCode, void * pExtra, AFX_CMDHANDLERINFO * pHandlerInfo) Line 989 C++ Symbols loaded. mfc140ud.dll!CWnd::OnCommand(unsigned __int64 wParam, __int64 lParam) Line 2801 C++ Symbols loaded. mfc140ud.dll!CFrameWnd::OnCommand(unsigned __int64 wParam, __int64 lParam) Line 384 C++ Symbols loaded. mfc140ud.dll!CWnd::OnWndMsg(unsigned int message, unsigned __int64 wParam, __int64 lParam, __int64 * pResult) Line 2113 C++ Symbols loaded. mfc140ud.dll!CWnd::WindowProc(unsigned int message, unsigned __int64 wParam, __int64 lParam) Line 2099 C++ Symbols loaded. mfc140ud.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 265 C++ Symbols loaded. mfc140ud.dll!CMDIFrameWnd::OnCommand(unsigned __int64 wParam, __int64 lParam) Line 43 C++ Symbols loaded. mfc140ud.dll!CWnd::OnWndMsg(unsigned int message, unsigned __int64 wParam, __int64 lParam, __int64 * pResult) Line 2113 C++ Symbols loaded. mfc140ud.dll!CWnd::WindowProc(unsigned int message, unsigned __int64 wParam, __int64 lParam) Line 2099 C++ Symbols loaded. mfc140ud.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 265 C++ Symbols loaded. mfc140ud.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 418 C++ Symbols loaded. mfc140ud.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 299 C++ Symbols loaded. user32.dll!UserCallWinProcCheckWow() Unknown Symbols loaded. user32.dll!DispatchMessageWorker() Unknown Symbols loaded. mfc140ud.dll!AfxInternalPumpMessage() Line 183 C++ Symbols loaded. mfc140ud.dll!CWinThread::PumpMessage() Line 900 C++ Symbols loaded. mfc140ud.dll!CWinThread::Run() Line 629 C++ Symbols loaded. mfc140ud.dll!CWinApp::Run() Line 787 C++ Symbols loaded. mfc140ud.dll!AfxWinMain(HINSTANCE__ * hInstance, HINSTANCE__ * hPrevInstance, wchar_t * lpCmdLine, int nCmdShow) Line 47 C++ Symbols loaded. App.MDI.exe!wWinMain(HINSTANCE__ * hInstance, HINSTANCE__ * hPrevInstance, wchar_t * lpCmdLine, int nCmdShow) Line 26 C++ Symbols loaded. App.MDI.exe!invoke_main() Line 123 C++ Symbols loaded. App.MDI.exe!__scrt_common_main_seh() Line 288 C++ Symbols loaded. App.MDI.exe!__scrt_common_main() Line 331 C++ Symbols loaded. App.MDI.exe!wWinMainCRTStartup(void * __formal) Line 17 C++ Symbols loaded. kernel32.dll!BaseThreadInitThunk() Unknown Symbols loaded. ntdll.dll!RtlUserThreadStart() Unknown Symbols loaded. ```

Repo steps (shows this works when shown as a modeless dialog)

  1. Modify the Interop project so that this block of code is executed: https://github.com/TechSmith/WebViewIssue/blob/main/Interop/Interop.cpp#L30-L36
  2. Run App.MDI as before
  3. Note that the WebView2 control works in this circumstance. šŸ¤·ā€ā™‚ļø

Repo steps (updating to the latest WebView2 control results in different error)

  1. Modify the referenced WebView2 NuGet package to 1.0.1150.38
    • (it's easier to just checkout the branch: update-nuget-1.0.1150.38)
  2. Rebuild the Solution
  3. Run App.MDI as before
  4. Note that there is a different exception now (even when trying to display as a modeless window, which worked before):
EnsureCoreWebView2Async cannot be used before the application's event loop has started running.
   at Microsoft.Web.WebView2.Wpf.WebView2.EnsureCoreWebView2Async(CoreWebView2Environment environment)
   at View.NET.WebViewControl.<InitializeWebView>d__8.MoveNext() in C:\src\WebViewIssue\View.NET\WebViewControl.xaml.cs:line 64
----- Call stack at the time of the above exception: ----- ``` > View.NET.dll!View.NET.WebViewControl.InitializeWebView() Line 64 C# Symbols loaded. View.NET.dll!View.NET.WebViewControl.OnSourcePropertyChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) Line 36 C# Symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.FrameworkElement.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e) Unknown No symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.NotifyPropertyChange(System.Windows.DependencyPropertyChangedEventArgs args) Unknown No symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.UpdateEffectiveValue(System.Windows.EntryIndex entryIndex, System.Windows.DependencyProperty dp, System.Windows.PropertyMetadata metadata, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry, bool coerceWithDeferredReference, bool coerceWithCurrentValue, System.Windows.OperationType operationType) Unknown No symbols loaded. WindowsBase.dll!System.Windows.DependencyObject.InvalidateProperty(System.Windows.DependencyProperty dp, bool preserveCurrentValue) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpressionBase.Invalidate(bool isASubPropertyChange) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.TransferValue(object newValue, bool isASubPropertyChange) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.Activate(object item) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.AttachToContext(System.Windows.Data.BindingExpression.AttachAttempt attempt) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(bool lastChance) Unknown No symbols loaded. PresentationFramework.dll!MS.Internal.Data.DataBindEngine.Task.Run(bool lastChance) Unknown No symbols loaded. PresentationFramework.dll!MS.Internal.Data.DataBindEngine.Run(object arg) Unknown No symbols loaded. PresentationCore.dll!System.Windows.ContextLayoutManager.fireLayoutUpdateEvent() Unknown No symbols loaded. PresentationCore.dll!System.Windows.ContextLayoutManager.UpdateLayout() Unknown No symbols loaded. PresentationCore.dll!System.Windows.Interop.HwndSource.SetLayoutSize() Unknown No symbols loaded. PresentationCore.dll!System.Windows.Interop.HwndSource.RootVisualInternal.set(System.Windows.Media.Visual value) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.SetRootVisual() Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.SetRootVisualAndUpdateSTC() Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.SetupInitialState(double requestedTop, double requestedLeft, double requestedWidth, double requestedHeight) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.CreateSourceWindow(bool duringShow) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.ShowHelper(object booleanBox) Unknown No symbols loaded. PresentationFramework.dll!System.Windows.Window.ShowDialog() Unknown No symbols loaded. View.NET.dll!View.NET.WebViewPresenter.ShowModal(System.IntPtr hWndParent) Line 29 C# Symbols loaded. Interop.dll!Interop::Show::Go(HWND__* hWndParent) Line 28 C++ Symbols loaded. Interop.dll!Interop::ShowWebView::Go(HWND__* hWndParent) Line 9 C++ Symbols loaded. [Native to Managed Transition] Annotated Frame App.MDI.exe!CAppMDIApp::OnFileOpenwebview() Line 78 C++ Symbols loaded. mfc140ud.dll!_AfxDispatchCmdMsg(CCmdTarget * pTarget, unsigned int nID, int nCode, void(CCmdTarget::*)() pfn, void * pExtra, unsigned __int64 nSig, AFX_CMDHANDLERINFO * pHandlerInfo) Line 78 C++ Symbols loaded. mfc140ud.dll!CCmdTarget::OnCmdMsg(unsigned int nID, int nCode, void * pExtra, AFX_CMDHANDLERINFO * pHandlerInfo) Line 372 C++ Symbols loaded. mfc140ud.dll!CFrameWnd::OnCmdMsg(unsigned int nID, int nCode, void * pExtra, AFX_CMDHANDLERINFO * pHandlerInfo) Line 989 C++ Symbols loaded. mfc140ud.dll!CWnd::OnCommand(unsigned __int64 wParam, __int64 lParam) Line 2801 C++ Symbols loaded. mfc140ud.dll!CFrameWnd::OnCommand(unsigned __int64 wParam, __int64 lParam) Line 384 C++ Symbols loaded. mfc140ud.dll!CWnd::OnWndMsg(unsigned int message, unsigned __int64 wParam, __int64 lParam, __int64 * pResult) Line 2113 C++ Symbols loaded. mfc140ud.dll!CWnd::WindowProc(unsigned int message, unsigned __int64 wParam, __int64 lParam) Line 2099 C++ Symbols loaded. mfc140ud.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 265 C++ Symbols loaded. mfc140ud.dll!CMDIFrameWnd::OnCommand(unsigned __int64 wParam, __int64 lParam) Line 43 C++ Symbols loaded. mfc140ud.dll!CWnd::OnWndMsg(unsigned int message, unsigned __int64 wParam, __int64 lParam, __int64 * pResult) Line 2113 C++ Symbols loaded. mfc140ud.dll!CWnd::WindowProc(unsigned int message, unsigned __int64 wParam, __int64 lParam) Line 2099 C++ Symbols loaded. mfc140ud.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 265 C++ Symbols loaded. mfc140ud.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 418 C++ Symbols loaded. mfc140ud.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned __int64 wParam, __int64 lParam) Line 299 C++ Symbols loaded. user32.dll!UserCallWinProcCheckWow() Unknown Symbols loaded. user32.dll!DispatchMessageWorker() Unknown Symbols loaded. mfc140ud.dll!AfxInternalPumpMessage() Line 183 C++ Symbols loaded. mfc140ud.dll!CWinThread::PumpMessage() Line 900 C++ Symbols loaded. mfc140ud.dll!CWinThread::Run() Line 629 C++ Symbols loaded. mfc140ud.dll!CWinApp::Run() Line 787 C++ Symbols loaded. mfc140ud.dll!AfxWinMain(HINSTANCE__ * hInstance, HINSTANCE__ * hPrevInstance, wchar_t * lpCmdLine, int nCmdShow) Line 47 C++ Symbols loaded. App.MDI.exe!wWinMain(HINSTANCE__ * hInstance, HINSTANCE__ * hPrevInstance, wchar_t * lpCmdLine, int nCmdShow) Line 26 C++ Symbols loaded. App.MDI.exe!invoke_main() Line 123 C++ Symbols loaded. App.MDI.exe!__scrt_common_main_seh() Line 288 C++ Symbols loaded. App.MDI.exe!__scrt_common_main() Line 331 C++ Symbols loaded. App.MDI.exe!wWinMainCRTStartup(void * __formal) Line 17 C++ Symbols loaded. kernel32.dll!BaseThreadInitThunk() Unknown Symbols loaded. ntdll.dll!RtlUserThreadStart() Unknown Symbols loaded. ```

Screenshots

Additional context

AB#38800459

champnic commented 2 years ago

Hey @dh0well - From the first issue, it sounds like you are accessing the CoreWebView2 from a different thread than it was created on. WebView2 is single-threaded, so you may need to dispatch a call to make sure you only access it from it's thread: https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/threading-model

The second issue points to not having an event loop running before trying to initialize the WebView2, which we need running to get our callbacks from the external processes. Is there an event loop running when you hit this error?

dh0well commented 2 years ago

Hey @dh0well - From the first issue, it sounds like you are accessing the CoreWebView2 from a different thread than it was created on.

Thank you for the response. The thread the object is created on appears to be the same as when the init. call is performed. See the attached images:

----- Screenshots of active threads at WebView2 construction and initialization calls (both are done on the same thread) ----- ## Right when the WebView2 control is about to be constructed: ![image](https://user-images.githubusercontent.com/5576185/161052020-45eadacf-8753-493c-bd45-33785c963734.png) ## At the time EnsureCoreWebView2Async() is called: ![image](https://user-images.githubusercontent.com/5576185/161052066-7c6c4603-e757-4153-a944-16607dd0c1ba.png)

Where it goes into a different thread is in that await. It makes me wonder whether the WebView2 implementation is attempting something in the resulting Task thread that it shouldn't be doing (i.e., an AcceleratorKeyPressed event handler). Can you look at that method (Microsoft.Web.WebView2.Core.Raw.ICoreWebView2Controller.add_AcceleratorKeyPressed()) and see if the caller can dispatch that action on the [main] thread the Ensure call was invoked on? That part is out of my control.

Note that it works fine if I open the window hosting the WebView2 control with System.Windows.Window.Show() rather than ShowDialog().

dh0well commented 2 years ago

The second issue points to not having an event loop running before trying to initialize the WebView2, which we need running to get our callbacks from the external processes. Is there an event loop running when you hit this error?

Yes, you can see that it is the MFC loop started in the CWinApp instance:

----- Call stack at the time of the WebView2 initialization ----- ![image](https://user-images.githubusercontent.com/5576185/161055134-a5fd8fee-9873-4a20-8a90-e7162a2fd9dd.png)

The point here is that it is the native (MFC) event loop and not one running in .NET. If I alter my application to run under a .NET loop (specifically: System.Windows.Threading.Dispatcher.Run();), then it works. But I don't want that, the application I am using is a legacy MFC application whose loop is started way back in AfxWinMain().

WebView2, in the most recent NuGet versions (1.0.1054.31 (11/29/2021) or later) seems to be fussy about there being a .NET event loop running. Is this by design now or possibly a bug?

champnic commented 2 years ago

This may be a bug with the way it's attempting to detect an event loop (as not having an event loop has caused difficult bugs in the past). I've opened this as a bug on our backlog and we'll take a look. Thanks!

yizhao5 commented 2 years ago

Hello, your problem is that when running App.MDI, and there is an exception of "EnsureCoreWebView2Async cannot be used before the application's event loop has started running".

  1. Cause Analysis:

We have debugged and located the cause in your example. The reason is that WFP requires UI threads, but there is no UI thread in your example. WPF or webview2 only provides Web control support, and the application and destruction of UI thread are better controlled by users. The user's scenario is CPP calling C# environment or other situations. In short, the UI thread is null during verification.

  1. Example of fixing:

WebViewIssue\View.NET\WebViewPresenter.cs

        public void ShowModal(IntPtr hWndParent)
        {
            var uiThread = new Thread(new ThreadStart(() =>
            {
                var window = new WebViewHostWindow()
                {
                    DataContext = new WebViewHostViewModel { Url = TestUrl }
                };

                window.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
                {
                    _ = new WindowInteropHelper( window ) { Owner = hWndParent };
                    _ = window.ShowDialog();
                });

                System.Windows.Threading.Dispatcher.Run();
            }));
            uiThread.SetApartmentState(ApartmentState.STA);
            uiThread.Start();
            uiThread.Join();
        }
  1. Test Results: passed. image

Hope that it helps you. Best regards.

dh0well commented 2 years ago

Hope that it helps you. Best regards.

Thank you for the analysis of that application and the resulting suggestion. I will give that a try at some point soon. šŸ‘