Web Development

Our forums are currently in maintenance mode and the ability to post is disabled. We will be back up and running as soon as possible. Thanks for your patience!

General discussion


Console Appliaction

By mansuk ·
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.

This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

All Comments

Collapse -

Console Appliaction

by andrew In reply to Console Appliaction

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"
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&amp
Next n
MsgBox "done"

CloseHandle hConsole
End Sub

This example is based on this MSDN article:


(make sure there are no spaces in the URL)

Collapse -

Console Appliaction

by mansuk In reply to Console Appliaction

thank you very much for your kindly help.

Collapse -

Console Appliaction

by mansuk In reply to Console Appliaction

This question was closed by the author

Related Discussions

Related Forums