0

I need to call a javascript function in a local web page loaded in Web Browser In WPF Form Using a thread Loop

This is my C# Code:

public partial class MainWindow : Window
    {


        Thread myThread;

        public MainWindow()
        {
            InitializeComponent();
            string WebPage = "file:///C:/Users/BARI/Desktop/JSThread/JavaScriptWithThread/JavaScriptWithThread/LocaWebPage.html";
            webBrowser.Navigate(WebPage);

        }

        private void ThreadLoop()
        {
            int i=0;
            while (Thread.CurrentThread.IsAlive)
            {
                Thread.Sleep(1000);
                try
                {
                    Console.WriteLine(i);
                    label.Dispatcher.Invoke(new Action(() => label.Content = i));
                    this.webBrowser.Invoke(new Action(() => this.webBrowser.InvokeScript("thread", i))); //Doesn't work


                }
                catch (InvalidOperationException)
                {
                    Console.WriteLine("Error!");
                }
                i++;
            }
        }

        private void StatrtThread_Button(object sender, RoutedEventArgs e)
        {
            this.webBrowser.InvokeScript("thread", "100"); //This works fine
            myThread = new Thread(new ThreadStart(ThreadLoop));
            myThread.Start();

        }

        private void StopThread_Button(object sender, RoutedEventArgs e)
        {
            myThread.Suspend();
        }
    }

my Html code :

<html>
    <head>
    <meta charset="utf-8">
    <title></title>
    </head>
<body onload=start()> 
<script>

function start(){
var t=0;
document.getElementById("valeur").innerHTML = t;
}
var i = 0;
function thread(i){

document.getElementById("valeur").innerHTML = i;
}


</script>

Valeur: <span id="valeur"></span>

</body>
</html>

I'm having an error in the this.webBrowser.Invoke(new Action(() => this.webBrowser.InvokeScript("thread", i))); WebBrowser doesn't contain a définition for Invoke any other solutions??

1 Answers1

0

Just do the same thing you do with the label in the line above it, use the Dispatcher.

this.webBrowser.Dispatcher.Invoke(new Action(() => this.webBrowser.InvokeScript("thread", i)));
J.H.
  • 4,232
  • 1
  • 18
  • 16