blog: Writing to console in Visual Basic 6

From a perspective of someone who has exclusively used Unix/Linux programming environments in his academic and private life, Visual Basic 6 really is an oddball - one that I have to deal with in work life, though. Since it lives on Windows, it has to deal with the weird separation of “subsystems”, which firmly divides console and graphical applications at link time. Your program can either be a console application, forcing a console to open even when you start it via the explorer, or it can be a graphical application, allowing no output to stdout.

And since VB was only meant for graphical applications, the programming environment does not expect you to link the program to the console subsystem. Consequently, VB6 also does not provide constructs to write to stdout.

You can still make it do so, it’s just a bit more painful:

Public Const STD_OUTPUT_HANDLE = -11&

Public Declare Function stdout Lib "kernel32" Alias "GetStdHandle" _
(Optional ByVal Handletype As Long = STD_OUTPUT_HANDLE) As Long

Public Declare Function WriteFile Lib "kernel32" _
(ByVal hFile As Long, ByVal lpBuffer As Any, ByVal nNumberOfBytesToWrite As Long, _
Optional lpNumberOfBytesWritten As Long, Optional ByVal lpOverlapped As Long = 0&) As Long


Dim hStdOut As Long
Dim sWriteBuffer As String

hStdOut = stdout()
sWriteBuffer = "Hello World"
WriteFile hStdOut, sWriteBuffer, Len(sWriteBuffer)

After compiling the .exe, you have to manually relink it to the console subsystem:

link /edit /subsystem:console application.exe

No wonder the whole “using one program’s output as another program’s input” thing isn’t more popular on Windows…

Posted in programming
2017-06-02 22:20 UTC