Rootel Rootel - 4 months ago 13
Vb.net Question

VB Console Application, no tasks auto-close

my fellow community members!
I'm creating my own Command Prompt and I want to know something about it.
When my program is out of a task, for example this code:

ElseIf cmdStr = "version" Then
Console.ForegroundColor = ConsoleColor.White
Console.Write("Current version: ")
Console.ForegroundColor = ConsoleColor.Yellow
Console.Write(appVersion)
Console.ForegroundColor = ConsoleColor.Black
Console.ReadLine()


After
Console.Readline()
there is empty space.
The console application will shutdown.
Is there anyway to let it do a task if there is no task?
I always put this in those empt spots:

Console.Clear
Main()


But I'm tired of doing that since i have almost reached 50 commands.
Is there a way? Thanks for your time!

Answer

If you are finding you are rewriting a lot of code for the commands look at refactoring them. You mention you are tired of calling clear and back into the main sub, but if this is common between all of your commands then you could do something like this:

Public MustInherit Class ConsoleCommand
    MustOverride Sub command
    Public sub run()
        command()
        Console.ReadLine()
        Main()
    End sub
End Class

Public Class VersionCommand
    Inherits ConsoleCommand
    Public Overrides Sub command()
        Console.ForegroundColor = ConsoleColor.White
        Console.Write("Current version: ")
        Console.ForegroundColor = ConsoleColor.Yellow
        Console.Write(appVersion)
        Console.ForegroundColor = ConsoleColor.Black
    End Sub
End Class


Public Class CommandFactory
    Public Function GetCommand(cmdStr As string) As ConsoleCommand
        Select Case cmdStr
            Case "version"
                Return New VersionCommand
            Case Else
                Return nothing
        End Select
    End Function
End Class

then in your main sub:

sub Main()

dim factory as new CommandFactory()
dim cmdText as string = Console.ReadLine()
dim command = factory.GetCommand(cmdText)
command.run()

end sub

Alternatively remove the

Console.ReadLine()
Console.Clear
Main()

from each if/else branch and place it after the End If

//In response to original posters comment around wanting to exit on "Close"

Sub Main()

dim cmdStr as string = String.Empty
do until cmdStr = "Close"
cmdStr = Console.ReadLine()
'Your if block goes here, minus the call back into main - which is now looping
loop

End Sub
Comments