Question

So I'm trying to teach myself object oriented programming using VB.net, and Although I have some basic experience with it, I feel that I'm doing something terribly wrong.

There are two visible screens (Forms) to my application, a "select your difficulty" screen that I'll refer to as screen1, and a "game" screen that I will refer to as screen2.

  1. I create a Main() class that runs when the application has loaded

  2. From within Main() I generate screen1 and screen2 (both Forms).

  3. Screen1 holds two buttons. When clicked, they will hide the current screen, display screen2, and begin the game with a set difficulty based on what button was chosen.

After jumping into the Form class, I can no longer reference Main(), where I would be able to close one form and open another with ease.

So the question is this. With regards to correct object oriented design. What is the most widely accepted way to change screens and start the game running?

I don't require code snippets or anything, I just need a basic explanation of how things should be done.

Was it helpful?

Solution

When you show the form from within your Main entry point method, you must be calling Application.Run. When you do so, execution does not continue to the next line in the Main method until the form is closed. So for instance, you could show the second form right after the first one is closed like this:

Sub Main()
    Application.Run(New Screen1())
    Application.Run(New Screen2())
End Sub

However, that's not typically how something like that is done. Typically, you would only call Application.Run once, on the first one, and then that form shows the second one. However, if you do that, you have to make sure the first form doesn't close until you want the program to end. So, rather than closing screen1, it should just hide itself. For instance:

Class Screen1
    Private Sub ShowScreen2()
        Dim screen2 As New Screen2()
        Me.Hide()
        screen2.Show()
    End Sub
End Class

Then, Screen1 could have an event handler to watch for when Screen2 closes and either re-show itself or close itself at that point. Or, if appropriate, you could show Screen2 as a dialog window which means execution won't continue in that method until the second screen is closed, for instance:

Class Screen1
    Private Sub ShowScreen2()
        Dim screen2 As New Screen2()
        Me.Hide()
        screen2.ShowDialog()
        Me.Show()
    End Sub
End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top