C#InvalidCastException的InvalidCastException

2023-09-07 09:39:46 作者:不过南柯一梦

我尝试使用这个code:

I try to use this code :

webBrowser.Document.GetElementById("login").SetAttribute("value", "user");

这工作的伟大,但不是当我用它在一个新的线程。我得到一个InvalidCastException。我该怎么办?

It work great but not when i use it in a new thread. I get an InvalidCastException. What can I do ?

推荐答案

这应该工作:

delegate void ActionExecutorOnUI(ref HtmlElement a, string b, string c);
private void SetValueOnHtmlElementOnUIThread(this HtmlElement onElement, string propToChange, string valueGiven, WebBrowser linkToWebBrowser)
        {
            if (linkToWebBrowser.InvokeRequired)
            {
                ActionExecutorOnUI d = new ActionExecutorOnUI(SetValueOnHtmlElementOnUIThread);
                linkToWebBrowser.Invoke(d, new object[] { });
            }
            else
                SetValueOnHtmlElementOnUIThread(ref onElement, propToChange, valueGiven);

        }

private void SetValueOnHtmlElementOnUIThread(ref HtmlElement onElement, string propToChange, string valueGiven)
        {
            onElement.SetAttribute("value", "user"); 
        }