February 28, 2021
Hot Topics:

Writing Console-Mode Applications in Visual Basic

  • By Scott Lloyd
  • Send Email »
  • More Articles »

Before we can call any other console functions, we'll need a handle to the console. Handles to the console window are just like handles to standard windows. When you use an API call to interact with a form window, you'll almost always have to provide the form's hWnd. When you use an API call to interact with a console window, you'll now have to provide one of its three handles--that's right, three. A console window has an input, output, and error handle. This is because each can be redirected, but that doesn't matter to us. We retrieve a handle with a call to GetStdHandle.

Private Declare Function _
GetStdHandle Lib "kernel32" (ByVal _
nStdHandle As Long) As Long

The argument nStdHandle determines which handle it returns. The mnemonic constants have three possible values to pass are:

Private Const STD_INPUT_HANDLE = -10&
Private Const STD_OUTPUT_HANDLE = -11&
Private Const STD_ERROR_HANDLE = -12&

Writing to the Console

So far you have learned how to create a console process and how to get a reference to it but you haven't learned anything terribly practical. To perform output to the console you must, of course, first have a handle to the output buffer. There are a few ways to print to the console, the most simplistic of them all being WriteConsole.

IMPORTANT NOTE: The Microsoft API Text Viewer declaration is incorrect. lpBuffer must be passed by value, even though it is of the long pointer type. This is because of a technical issue with the way strings are passed and stored in C.

Private Declare Function WriteConsole _
    Lib "kernel32" _
    Alias "WriteConsoleA" _
    (ByVal hConsoleOutput As Long, _
    ByVal lpBuffer As Any, 
    ByVal nNumberOfCharsToWrite As Long, _
    lpNumberOfCharsWritten As Long, _
    lpReserved As Any) As Long

This function is slightly more complicated than the previous ones. Here, the first argument is the console's output handle. This is obtained by passing STD_OUTPUT_HANDLE to GetStdHandle. The second argument is set to the length of lpBuffer. The third argument is the string buffer. The third argument is a pointer to a variable that will be set to the number of charactors that were actually written. The fourth and final argument is always vbNull. This may all seem complicated, but the example should set you straight.

Page 3 of 7

This article was originally published on November 20, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date