Home > Code Dump > Console Support in Visual Basic 6 (VB6)

Console Support in Visual Basic 6 (VB6)

Spawn and output to a Windows Console from a VB form application
By 28/12/10 [Last Edited by Joseph 09/01/11]
BOOKMARK
LOGIN
REGISTER
Using the Windows API, you can spawn and output to a Windows Console alongside your VB6 form application. First of all, create a new module, and paste the following code into it.

Separate Module Code

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
Public Const STD_OUTPUT_HANDLE = -11&

Code to Include

Code to include in your main (calling) application.

Declare the global variable:

Dim hConsole

Place the following code in your Form_Load() subroutine:

If AllocConsole() Then
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
    If hConsole = 0 Then MsgBox "Couldn't allocate STDOUT"
Else
    MsgBox "Couldn't allocate console"
End If

Place the following snippets of code in your program:

Sub Form_UnLoad(Cancel As Integer)
    closeCons
End Sub

Sub closeCons() 'Close the console
    CloseHandle hConsole
    FreeConsole
End Sub

Sub addCons(ByVal szEntry As String) 'Add the string to the console
    Dim Result As Long, szOut As String, cWritten As Long
    szOut = szEntry & vbCrLf
    Result = WriteConsole(hConsole, ByVal szOut, Len(szOut), cWritten, ByVal 0&)
End Sub

Usage

It's basically all done for you, simply call addCons("Your text here")