Search code examples
javascript.netwpfdotnetbrowser

dotnetbrowser Calling .NET from JavaScript - ThreadProblem


[dotnetbrowser] Calling .NET from JavaScript - ThreadProblem

i am using vb net , vs 2017 and WPF, no mvvm.

My Wpf Mainwindow contains a dotnetbrowser-Webbrowser control (evaluation only). Looks this way:

            <wpf:WPFBrowserView x:Name="WebBrowser1" Background="Transparent"  Panel.ZIndex="1110"  
                                Margin="-5,-5,0,0"   Grid.ColumnSpan="2" 
                        BrowserType="LIGHTWEIGHT"           VerticalAlignment="Top" HorizontalAlignment="Left"
                                 Width="300" Height="300" >
                <wpf:WPFBrowserView.Preferences>
                    <DotNetBrowser:BrowserPreferences TransparentBackground="True"/>
                </wpf:WPFBrowserView.Preferences>
            </wpf:WPFBrowserView>

I defined an event like this:

         AddHandler WebBrowser1.Browser.ScriptContextCreated,
                    Sub(sender As Object, e As ScriptContextEventArgs)
                        Dim value As JSValue = WebBrowser1.Browser.ExecuteJavaScriptAndReturnValue("window")
                        value.AsObject().SetProperty("Account", New Account())
                    End Sub

The account looks like this:

    Public Class Account
        Public Sub Save(firstName As String, lastName As String)
            Try
                MessageBox.Show(firstName & " " & lastName)
                Dim freileg As New winLeg(firstName)
                freileg.Show()

            Catch ex As Exception
                l(ex.ToString())
            End Try
        End class

The messagebox shows firstname lastname correctly. But the new WPFWindow(winleg) smashes error:

Beim aufrufenden Thread muss es sich um einen STA-Thread handeln, da dies 
für viele Komponenten der Benutzeroberfläche erforderlich ist.

(engl: the calling thread must be STA cause its nessesary for many components of the UI)

I need the returned data within my main wpf-window thread. I am not really used to Threading (except Backgroundworker) so i am clueless. Any help would be appreciated.


Solution

  • Try to invoke your code using the application dispatcher. Here is the sample Account implementation:

    Public Class Account
        Public Sub Save(firstName As String, lastName As String)
            Application.Current.Dispatcher.BeginInvoke(
                    Sub()
                        Try
                            Dim window As New Window()
                            window.Title = firstName & " " & lastName
                            window.Width = 320
                            window.Height = 240
                            window.Show()
                        Catch ex As Exception
                            Debug.WriteLine(ex.ToString())
                        End Try
                    End Sub)
        End Sub
    End Class