【问题标题】:Use object from other thread使用来自其他线程的对象
【发布时间】:2015-03-01 09:52:20
【问题描述】:

我需要使用没有表单的 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 始终为 false 我该怎么办?

【问题讨论】:

    标签: c# activex


    【解决方案1】:

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

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

    public void A()
    {
        // ...
    
        rdp.CreateControl();
        rdp.CreateHandle(); // Create handle for Control.
    
        // ...
    
    }
    

    另外,根据MSDN

    继承人须知 在派生类中重写 CreateHandle 时, 请务必调用基类的 CreateHandle 方法以确保 句柄已创建。

    因此,如果您拥有 AxMsRdpClient9NotSafeForScripting,如果您要覆盖 CreateHandle,则更好的位置是 base.CreateHandle()

    【讨论】:

    • rdp.CreateHandle get Compilation error 'System.Windows.Forms.Control.CreateHandle()' 由于其保护级别和 base.CreateHandle get 'object' 不包含 'CreateHandle 的定义而无法访问'
    • 我的错。 AxMsRdpClient9NotSafeForScripting 到底是什么?
    • 尝试将rdp.EndInit();放在rdp.CreateControl();之后
    • 它继承了什么?它做什么都没关系。重要的是它是什么。能给我看看代码吗?
    猜你喜欢
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2023-03-21
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多