繁体   English   中英

在线程循环内调用JavaScript函数

[英]Invoke JavaScript function inside a Thread Loop

我需要使用线程循环在WPF表单中的Web浏览器中加载的本地网页中调用javascript函数

这是我的C#代码:

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();
        }
    }

我的HTML代码:

<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>

我在this.webBrowser.Invoke(new Action(() => this.webBrowser.InvokeScript("thread", i))); WebBrowser没有包含调用任何其他解决方案的定义?

使用分派器,只需对标签上方的行中的标签执行相同的操作即可。

this.webBrowser.Dispatcher.Invoke(new Action(() => this.webBrowser.InvokeScript("thread", i)));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM