Running a DOS command

Occasionally you might find that you want to run a dos command from your VB program. The easiest way to do this is create a batch file (*.bat) containing the command (ie registering a number of components). Your program can then call this file, and wait until it has finished using the code below

Private Sub cmdDos_Click()
    Dim lngTask As Long, lRet As Long, pHandle As Long
    '// start the dos program
    lngTask = Shell(App.Path & "pointless.bat", vbMinimizedNoFocus)
    '// get a handle on the window
    pHandle = OpenProcess(SYNCHRONIZE, False, lngTask)
    lblStatus.Caption = "Running DOS program..."
    lblStatus.Refresh
    cmdDOS.Enabled = False
    Do
        '// you can pass INFINITE instead of 0 if you wish, and your
        '// program will 'hang' here until the program is finished
        lRet = WaitForSingleObject(pHandle, 0)
        DoEvents
    Loop While lRet <> 0
    lblStatus.Caption = "Finished"
    
    lRet = CloseHandle(pHandle)  'Close the task
    cmdDOS.Enabled = True
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If cmdNotepad.Caption = "Close Notepad" Then Call cmdNotepad_Click
End Sub

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” - Donald Knuth