不能在尚未创建的控件上调用Invoke或begininvoke

本文关键字:调用 Invoke begininvoke 控件 创建 不能 | 更新日期: 2023-09-27 17:48:56

我有一个正常的Windows Forms应用程序,但得到以下错误:

Invoke or begininvoke cannot be called on a control which is not yet created.

这发生在以下代码中:

Application.ThreadException += Application_ThreadException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var args = new string[0];
new MyApp().Run(args);

我用的是闪屏,我想这就是问题开始的地方。

如何解决?

不能在尚未创建的控件上调用Invoke或begininvoke

为什么要将参数传递给自己的应用程序?Windows Forms应用程序的默认入口点定义不接受任何参数,所以您是否手动更改了它?

解决你的问题,试着用这个代替:

Application.Run(new YourMainForm());

所以,最终:

Application.ThreadException += Application_ThreadException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new YourMainForm());

为了检索由执行程序传递给应用程序的参数,您可以使用暴露GetCommandLineArgs方法的Environment类。因此,如果您需要确定这些值,您可以A)调用此方法,解析然后通过属性或类似的方式以强类型格式存储,或者B)调用此方法,按需解析,例如,从您的表单中。

我刚刚点击的一个老帖子-似乎有一个MS错误重新抬头,几乎是随机的,尽管有些机器似乎比其他机器受影响更严重。

感谢Gallagher先生为我指出了MSDN的社交文章和解决方法。

诀窍是帮助框架意识到闪屏实际上是可用的,不让它隐藏闪屏,直到它被正确创建。

所以添加一个SplashLoadFinished标志作为用户设置或类似的。

然后在Splash Form.Load事件中设置此标志(下面的行必须分别是第一行和最后一行):

Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    My.Settings.SplashLoadFinished = False
    ...
    My.Settings.SplashLoadFinished = True
End Sub

然后在ApplicationEvents Startup事件中放置一个等待循环:

Private Sub MyApplication_Startup(sender As Object, e As ApplicationServices.StartupEventArgs) Handles Me.Startup
...
If (Me.SplashScreen IsNot Nothing) Then
    'Wait until the Splash has actually been created
    While (Not My.Settings.SplashLoadFinished)
        System.Threading.Thread.Sleep(50)
    End While
End If
...