Sen
Sen

Reputation: 85

ElementHost gives me "The calling thread must be STA, because many UI components require this."

I just added an ElementHost to a windows Form(There are some other c# code in the Form). Then it gave me the error "The calling thread must be STA, because many UI components require this." I changed the thread to STA, but it blocked other things...is there anyway to make the elementhost work without touching any other code?

here is the code how i change thread:

public UCClientSummary()
    {
        InitializeComponent();

        Thread thread = new Thread(createElementHost);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();


    }

    public void createElementHost()
    {
        ElementHost elementHost = new ElementHost();
        elementHost.Dock = DockStyle.Fill;
        LDControls.ucCell uc = new LDControls.ucCell();
        elementHost.Child = uc;
        this.Controls.Add(elementHost);
    }

Upvotes: 0

Views: 1220

Answers (1)

Mario The Spoon
Mario The Spoon

Reputation: 4869

Add the [STAThread] attrribute in front of your main. I am not sure if switching thread apartment state in between works.

It may be that the background workers are already created in the wrong apartment state.

hth

Mario

Upvotes: 0

Related Questions