Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I run and control a DOS console?

Windows API

How do I run and control a DOS console?

by  MikeLacey  Posted    (Edited  )
This was contributed by Eric De Decker and runs fine under Win98 and with VB6. As with all applications that use the Win32 API you should test it carefully before relying upon it.

Eric doesn't seem to be active on Tek-Tips anymore so I'm creating this FAQ from his posting and will correct any mistakes and add any enhancements people suggest. If it doesn't work, or you have problems with it, please send your comments to me rather than to Eric. If Eric becomes active on Tek-Tips again I'm happy to pass it back to him.

Mike.

Create a new standard project, add a command button to the form, double click the form and paste this code into the code window - it must completely replace the default code already there.
[tt]
Option Explicit

' Copyright Eric De Decker
' vbg.be@vbgroup.nl
' Visual Basic Center

Private Declare Function AllocConsole Lib "kernel32" () As Long

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

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

Private Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Long _
) As Long

Private Declare Function FreeConsole Lib "kernel32" () As Long

Private Const STD_OUTPUT_HANDLE = -11&
Private hConsole As Long

Private Sub Form_Load()

Dim txt As String
Dim num_written As Long

If AllocConsole() Then
hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
If hConsole = 0 Then
MsgBox "Couldn't allocate STDOUT"
Else
' Present a warning.
txt = "******************************************" & vbCrLf & _
"* Warning: Do not close this window! *" & vbCrLf & _
"* Close the VB program's window instead. *" & vbCrLf & _
"******************************************" & vbCrLf
WriteConsole hConsole, txt, Len(txt), num_written, vbNullString

' Make this form visible and on top.
Me.Show
SetFocus
End If
Else
MsgBox "Couldn't allocate console"
End If

End Sub
Private Sub Command1_Click()

Dim txt As String
Dim num_written As Long

txt = "Ready to run" & vbCrLf
WriteConsole hConsole, txt, Len(txt), num_written, vbNullString
Shell "c:\rundir.bat"

'
' c:\rundir.bat contains the following line
' dir
'

End Sub

Private Sub Form_Unload(Cancel As Integer)
CloseHandle hConsole
FreeConsole
End Sub
[/tt]

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top