Discussion Locked

Console Appliaction

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi
i want to a write a simple console application in vb which will print numbers from 1 to 10 in a loop. can anybody tell me how i can do this.
Thanx

3 replies

by andrew

Writing a VB console app is as easy as creating an EXE project with no form, and a single standard module (.bas) with a Sub Main() method.

Now, writing to the console from VB is *quite* tricky. When the app starts, VB disconnects it from the console, so there's no handle to write back to. The example below creates a new console window (using the Win32 API) and then outputs to it.

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&

Sub Main()
Dim hConsole As Long
Dim Result As Long, sOut As String, cWritten As Long
Dim n As Integer

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

For n = 1 To 10
sOut = CStr(n) & vbCrLf
Result = WriteConsole(hConsole, ByVal sOut, Len(sOut), cWritten, ByVal 0&)
Next n
MsgBox "done"

CloseHandle hConsole
FreeConsole
End Sub

This example is based on this MSDN article:

http://support.microsoft.com/support/kb/articles/Q171/6/54.asp

(make sure there are no spaces in the URL)

This discussion is closed to new replies.