使用来自其他线程的对象

时间:2015-03-01 09:52:20

标签: c# activex

我需要使用没有表单的ActiveX对象。我找到了解决方案here,编写相同的代码

public class C
{
    private AxMsRdpClient9NotSafeForScripting rdp;
    private Thread thread;

    public void B()
    {
        rdp.Invoke(new MethodInvoker(delegate
        {
            rdp.Connect();
        }));           
    }

    public void A()
    {
        thread = new Thread((ThreadStart)
            {
                rdp = new AxMsRdpClient9NotSafeForScripting();
                rdp.BeginInit();
                rdp.CreateControl();

                //more

                Application.Run();
            });

        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Start();
    }
}

在方法B中,我有异常“在创建窗口句柄之前,无法在控件上调用InvokeEvent:Invoke或BeginInvoke”。 rdp.InvokeRequired总是假的; rdp.IsHandled总是假的我该怎么办?

1 个答案:

答案 0 :(得分:0)

我不确定你在做什么。但我之前有过这个错误。

假设AxMsRdpClient9NotSafeForScripting继承Control,以下内容可能有所帮助:

public void A()
{
    // ...

    rdp.CreateControl();
    rdp.CreateHandle(); // Create handle for Control.

    // ...

}

另外,根据MSDN

  

对继承者的说明   在派生类中重写CreateHandle时,   一定要调用基类的CreateHandle方法来确保   句柄已创建。

因此,如果您取代AxMsRdpClient9NotSafeForScripting,如果您拥有base.CreateHandle()更好的地方CreateHandle

相关问题