如何在C#

我试图实例化 WebBrowser 类的对象以在页面上进行查询并返回结果,但是会生成错误:

  

由于当前线程不在未处理的容器中,因此无法创建activeX控件'8856f961-340a-11d0-a96b-00c04fd705a2'的实例。

我试图以不同的方式实现这一目标,但没有达到预期的结果。

这是我的代码

// At beginig of class Form
public delegate void DataRecieved(ConexionTcp conexionTcp,string data);
public event DataRecieved OnDataRecieved;

private void Form1_Load(object sender,EventArgs e)
{
    OnDataRecieved += MensajeRecibido;
}
private void MensajeRecibido(ConexionTcp conexionTcp,string datos)
{
    WebBrowser myweb= new WebBrowser();
    myweb.Navigate("http://localhost/Php/Final3");
    myweb.Document.GetElementById("user").InnerText = "user";
    myweb.Document.GetElementById("pass").InnerText = "pass";
    myweb.Document.GetElementById("Encode").InvokeMember("Click");
    if ("resultado" == myweb.Document.GetElementById("pass_sha_hash").InnerText)
    { 
        textbox1.Text="Completado";
    }
}

有人能找出我在做什么错吗?

nancy69669 回答:如何在C#

好像您正在尝试从线程访问Windows窗体控件。

从另一个线程访问Windows窗体控件是不安全的。因此,您会收到此错误。

有关更多详细信息,请参阅此文档:https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls

您可以使用后台线程进行操作。否则,将线程的驻留状态标记为STA可能会有所帮助。

在下面的示例中,我使用了STA线程,否则,我将收到类似的错误。

public partial class Form1 : Form
{
    Thread t;
    public delegate void DataRecieved();
    public event DataRecieved OnDataRecieved;

    public Form1()
    {
        InitializeComponent();

        t = new Thread(new ThreadStart(this.TriggerEvent));

        // Make sure that you are using STA
        // Otherwise you will get an error when creating WebBrowser
        // control in the Navigate method
        t.SetApartmentState(ApartmentState.STA);
        t.Start();

        OnDataRecieved += Navigate;
    }

    public void Navigate()
    {
        WebBrowser b = new WebBrowser();
        b.Navigate("www.google.com");
    }

    public void TriggerEvent()
    {

        Thread.Sleep(10000);
        OnDataRecieved();
    }
}

以下是错误:

System.Threading.ThreadStateException: 'ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.'

希望这会有所帮助。

本文链接:https://www.f2er.com/3127268.html

大家都在问