Question

Hi guys i'm stuck at a part of my program when I want to make a screen start up only once then go to the main screen here is my Form 1's code

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    My.Settings.Done = "Finished"
    My.Settings.Save()
    Me.Hide()
    Form2.Show()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    If My.Settings.Done = "Finished" Then
        Me.Hide()
        Form2.Show()
    Else

    End If
End Sub

End Class

I have also put the string variables in the setting of the form's properties But every time I try running it after the first time I will always get two forms how can I make it show the second form only after the first time the user has clicked the button?

Thanks

Was it helpful?

Solution

This is a Winforms quirk. The Form.Hide() method sets the Visible property to False. The Visible property is a Really Big Deal in Winforms. In typical .NET style, the native window of a form gets created in lazy fashion, as late as possible. It is the Visible property that gets the wagon rolling, setting it true triggers a large chain of code. Including creating the native window for the form, as well as the native windows for all the controls, any automatic scaling as required. And the Load event is triggered.

That's where the quirk comes into play, the Load event is triggered because Visible was set to True. Setting it to False in a Load event handler has no effect, that would "undo" the reason it was fired in the first place. Makes somewhat sense when explained like this, of course makes little sense when you run into this behavior.

There are more problems caused by your code even if it did work. You still have a hidden form. It keeps your program running even when the user closes the only visible window. That's not good.

One thing that works is closing the form. You'll need to change a setting. Project + Properties, Application tab. Change the Shutdown mode option to "When last form closes". Now you can write it like this:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    If My.Settings.Done = "Finished" Then
        Form2.Show()
        Me.Close()
    End If
End Sub

But the much cleaner solution is to just pick the right first form to display. Project + Properties, Application tab, click the "View Application Events" button. Add the Startup event:

    Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
        If My.Settings.Done = "Finished" Then Me.MainForm = New Form2()
    End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top