Library code snippets

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

Comments

  1. 22 Apr 2009 at 23:09
    Or you could use the third parameter in the 'Shell' function to tell your program to wait until the batch file is done. Shell(App.Path & "pointless.bat", vbMinimizedNoFocus, True)
  2. 05 Jun 2002 at 10:05
    OpenProcess is an API function
  3. 03 Jun 2002 at 10:14

    The example code uses a function:    OpenProcess
    I cannot find out where, or how to use, this function

  4. 01 Jan 1999 at 00:00

    This thread is for discussions of Running a DOS command.

Leave a comment

Sign in or Join us (it's free).

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 ...

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

We'd love to hear what you think! Submit ideas or give us feedback