我需要在Web浏览器中加载的本地网页中调用javascript函数在WPF表单中使用线程循环
这是我的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不包含Invoke的定义
任何其他解决方案??
答案 0 :(得分:0)
只需对上面的行中的标签执行相同的操作,请使用Dispatcher。
this.webBrowser.Dispatcher.Invoke(new Action(() => this.webBrowser.InvokeScript("thread", i)));