Hello, World! in Basic

Example for versions Microsoft Visual Basic 6

The intended use of Visual Basic is GUI applications development, so creating a simple console application is a non-trivial task itself. This example features:

  • importing required functions from standard library;
  • console creation;
  • getting the handle of console output stream;
  • writing the message to this stream and
  • deallocation of used objects.
Option Explicit

    Declare Function AllocConsole Lib "kernel32" () As Long
    Declare Function FreeConsole Lib "kernel32" () As Long
    Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    Declare Function GetStdHandle Lib "kernel32" (ByVal nStdHandle As Long) As Long
    Declare Function WriteConsole Lib "kernel32" Alias "WriteConsoleA" _
           (ByVal hConsoleOutput As Long, lpBuffer As Any, ByVal _
           nNumberOfCharsToWrite As Long, lpNumberOfCharsWritten As Long, _
           lpReserved As Any) As Long
    Declare Function Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) As Long

Private Sub Main()
    'create a console instance
    AllocConsole
    'get handle of console output
    Dim hOut As Long
    hOut = GetStdHandle(-11&)
    'output string to console output
    Dim s As String
    s = "Hello, World!" & vbCrLf
    WriteConsole hOut, ByVal s, Len(s), vbNull, vbNull
    'make a pause to look at the output
    Sleep 2000
    'close the handle and destroy the console
    CloseHandle hOut
    FreeConsole
End Sub