【问题标题】:InvokeEvent: Invoke or BeginInvoke cannot be called on a control until the window handle has been createdInvokeEvent:在创建窗口句柄之前,不能对控件调用 Invoke 或 BeginInvoke
【发布时间】:2011-04-08 08:20:05
【问题描述】:
private void manager_OnWebSiteVisited(object source, WebSiteVisitedEventArgs args)
        {
            if (InvokeRequired)
                txtStatus.BeginInvoke(new WebSiteVisitedCallback(WebSiteVisited), new object[] { args });
            else
                txtStatus.Invoke(new WebSiteVisitedCallback(WebSiteVisited), new object[] { args });
        }

InvokeEvent:在创建窗口句柄之前,不能对控件调用 Invoke 或 BeginInvoke。

我可以使用 if (IsHandleCreated) 但我不知道如果没有创建该怎么办。如何创建?

【问题讨论】:

    标签: c#


    【解决方案1】:

    只需访问Handle 属性,如果尚未创建句柄,它将创建句柄。也可以显式调用CreateHandle 方法。

    if (!this.IsHandleCreated)
    {
        this.CreateHandle();
    }
    

    顺便说一句,你对InvokeRequired/Invoke/BeginInvoke的使用是错误的:如果InvokeRequired是假的,你根本不应该使用Invoke,你应该直接调用该方法。我想你想做的是这样的:

            if (InvokeRequired)
                txtStatus.Invoke(new WebSiteVisitedCallback(WebSiteVisited), new object[] { args });
            else
                WebSiteVisited(args);
    

    【讨论】:

    • 只需访问 Handle 属性。你到底是什么意思。
    • 我的意思是获取属性的值。但无论如何,显式创建句柄可能会更干净。请参阅我更新的答案中的代码
    猜你喜欢
    • 2010-10-22
    • 2021-05-14
    • 1970-01-01
    • 2023-01-10
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多