I have a splash-screen for a desktop app that I am making. The way the startup works is that it checks for certain files, if it finds them it closes immediately and loads up the main form.
However by doing so I get a threading error. I'm guessing its because the startup form closes before fully loading the Main form.
Here's the error message:
Cross-thread operation not valid: Control 'frm_SplashScreen' accessed from a thread other than the thread it was created on.
I've tried putting the thread to sleep, and even using timers to give the form time to load. But so far unsuccessfully.
Private Sub frm_Load_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Dir("System.dll") = "" then
Createfile()
Frm_Main.show()
Me.close()
Else
Frm_Main.show()
Me.close()
End IF
Everything else regarding the splash-screen is done in the project properties under application. Otherwise it is just an empty form.
How can I fix this?
In WinForms, the splash screen is not responsible for creating the main form and should not do so. If you have code that needs to run before the main form is created, while the splash screen is visible, place that code in the application's Startup
event. Here's how to do it:
Private Sub MyApplication_Startup(sender, e) Handles Me.Startup
).If Dir(...) Then Createfile()
stuff in your example code) in the event handler.The code in the Startup event handler will be called before the main form is created. The splash screen will automatically be created, displayed, and destroyed in another thread. You don't need to worry about creating or closing the splash screen, as that is done automatically.
If your startup code determines that you don't want the main form to be displayed at all, set e.Cancel = true
in the startup event handler method and the application will quit instead of bringing up the main form.