c# - “Invoke or BeginInvoke cannot be called on a control until the window handle has been created”仅在第二次打开表单时出现

标签 c# multithreading winforms delegates

我正在开发的应用程序是现有应用程序的插件,并且第一次运行该插件时,一切工作正常。但是,当我第二次打开插件时,出现错误:

未处理InvalidOperationException-在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke。

我了解比赛条件,从我读到的所有内容中,尝试在HandleCreated为真之前访问表单元素时都会发生此错误,但是我无法弄清楚为什么只有第二次打开插件时才会发生这种情况。

这是插件代码。调用SetProgressBar()时发生错误:

    private MainForm mainForm;

    public void StartPlugin()
    {
        mainForm  = new MainForm (this);
        mainForm .ShowDialog();
    }

    public bool GetJoinEnabled()
    {
        mainForm.SetProgressBar(3);
    }

这是我的主要形式:
    private Thread m_JoinThread;
    private JoinPlugin m_Join;

    public MainForm(JoinPlugin zig)
    {
        m_Join = zig;
        InitializeComponent();
        m_JoinThread= new Thread(new ThreadStart(GetJoinData));
        m_JoinThread.Start();
    }

    private void GetJoinData()
    {
       //Get enable join data
        bool result = m_Join.GetJoinEnabled();
    }

    public void SetProgressBar(int value)
    {
        SetProgressCallback del = new SetProgressCallback(SetProgressBarControl);
        this.Invoke(del, value);
    }

    private void SetProgressBarControl(int value)
    {
        progressBar.Value = value;
    }

最佳答案

我有点猜测,但是前段时间我遇到了同样的问题。

您正在表单构造函数中启动线程:

m_JoinThread.Start();

这将立即启动线程并在某处调用Invoke。目前,表格尚未完全初始化。
将代码移到Load事件:
public ZigbeeJoinForm_Load()
{
    m_JoinThread= new Thread(new ThreadStart(GetJoinData));
    m_JoinThread.Start();
}

这样可以确保表单已完全初始化,然后调用Invoke是安全的。

关于c# - “Invoke or BeginInvoke cannot be called on a control until the window handle has been created”仅在第二次打开表单时出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17603339/

相关文章:

C# 时间轴控件

c# - 如何使用 PLINQ 在 C# 中实现 MapReduce?

c# - GridView 人口

c# - ASP.NET MVC 4 中的 ServerManager.OpenRemote 错误 80040154 CLSID {2b72133b-3f5b-4602-8952-803546ce3344}

c# - 使用 XmlSerializer 反序列化具有选择的复杂类型元素

c# - 错误 : Must create DependencySource on same Thread as the DependencyObject even by using Dispatcher

java - 从可运行类内部中断线程? (java)

c++ - 装修调度系统

winforms - 在 Windows 窗体 C# .NET 中查找控件?

c# - 不能在数据绑定(bind) datagridview 控件上设置列计数属性 c#