I have the following C# code to get a DIV's html element text value from a .NET Windows Forms WebBrowser control:
private void cmdGetText_Click(object sender, EventArgs e)
{
string codeString = string.Format("$('#testTextBlock').text();");
object value = this.webBrowser1.Document.InvokeScript("eval", new[] { codeString });
MessageBox.Show(value != null ? value.ToString() : "N/A", "#testTextBlock.text()");
}
private void myTestForm_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText =
@"<!DOCTYPE html><html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<div id='testTextBlock'>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</div>
</body>
</html>";
}
It works well. It works synchronously.
Here is the first asynchronous variation of cmdGetText_Click method:
private async void cmdGetText_Click(object sender, EventArgs e)
{
string codeString = string.Format("$('#testTextBlock').text();");
object value = await Task.Factory.StartNew<object>(() =>
{
return this.Invoke(
new Func<object>(() =>
{
return
this.webBrowser1.Document
.InvokeScript("eval", new[] { codeString });
}));
});
MessageBox.Show(value != null ? value.ToString() : "N/A", "#myTestText.text()");
}
And here is the second asynchronous variation of cmdGetText_Click method:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class myTestForm : Form {
...
private async void cmdGetText_Click(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
string codeString = string.Format("window.external.SetValue($('#testTextBlock').text());");
await Task.Run(() =>
{
this.Invoke((MethodInvoker)(()=>{this.webBrowser1.Document.InvokeScript("eval", new[] { codeString });}));
});
}
public void SetValue(string value)
{
MessageBox.Show(value != null ? value.ToString() : "N/A", "#myTestText.text()");
}
Question: Are there any other practical asynchronous variations of original cmdGetText_Click method, variations which would use some other approaches than presented here? If you post them here could you please post also your reasons why would you prefer your approach of a coding solution of the subject task.
Thank you.
[UPDATE]
Here is a screenshot demonstrating that WebBrowser control is accessed in the first sample/async variant from UI thread.
[UPDATE]
Here is a screenshot demonstrating that WebBrowser control is accessed in the second sample/async variant from UI thread.