how can we run a dos command from VB
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: how can we run a dos command from VB

  1. #1
    Join Date
    Jan 2002
    Posts
    8

    how can we run a dos command from VB

    i tried to execute any dos command(like md , cd, ftp,etc) from VB but i am not able to do that.i am able to run an executable file by giving the path in the shell method:as follows.

    Private Sub Command1_Click()
    Shell ("C:\WINNT\system32\cmd.exe")
    End Sub

    this opens the dos prompt.

    but how to run a command like md,cd,dir,etc. from VB.if there is any way then please tell me.also try to send a sample code if you can.

    thanks and regards
    sumit


  2. #2
    Join Date
    Feb 2001
    Location
    PA
    Posts
    163

    Re: how can we run a dos command from VB

    Try making a batch (.bat) file and running that with the shell command.


  3. #3
    Join Date
    Jul 2000
    Location
    Milano, Italy
    Posts
    7,726

    Re: how can we run a dos command from VB

    [From Cimp:]Better you look at next answer from softweng before trying this old code..

    Code:
    'This code will create "abcd" directory in current Path.
    'You cannot debug normally: to work this need the dos
    'window to have focus
    'If you want to see dos window, comment the
    'last commands that close that window
    option Explicit
    
    private Sub Command1_Click()
    
    Dim strCommand as string
    Dim retPointer as Long
    
    '
    'if winNt
    retPointer = Shell("cmd.exe", vbMaximizedFocus)
    
    'if win98/95/me, the following:
    'retPointer = Shell("command.exe", vbMaximizedFocus)
    '
    'launch a command:
    'activate the dos window
    AppActivate retPointer
    'put the command in string variable -start with a space!-
    strCommand = " mkdir abcde"
    'write it to the dos window:
    SendKeys strCommand, true
    'you've just typed something. Need to press enter?
    SendKeys "{ENTER}", true
    
    'close dos windows:
    SendKeys "Exit", true
    SendKeys "{ENTER}", true
    End Sub
    '
    'Have a nice day,
    'Cesare Imperiali
    '
    'On dos prompt see also:
    http://www.codeguru.com/forum/showth...&highlight=Dos

    http://hem.spray.se/mattias.sjogren/bin/cmdoutput.zip

    http://www.codeguru.com/forum/showth...&highlight=Dos


    http://www.codeguru.com/forum/showth...&highlight=Dos

    http://www.codeguru.com/forum/showth...&highlight=Dos




    Special thanks to Lothar "the Great" Haensler, Tom Archer, Chris Eastwood, TCartwright, Bruno Paris, Dr_Michael
    and all the other wonderful people who made and make Codeguru a great place.
    Come back soon, you Gurus.

    The Rater
    Last edited by Cimperiali; August 25th, 2003 at 10:09 AM.
    ...at present time, using mainly Net 4.0, Vs 2010



    Special thanks to Lothar "the Great" Haensler, Chris Eastwood , dr_Michael, ClearCode, Iouri and
    all the other wonderful people who made and make Codeguru a great place.
    Come back soon, you Gurus.

  4. #4
    Join Date
    Mar 2000
    Location
    Arizona, USA
    Posts
    493

    Re: how can we run a dos command from VB

    This works well for me. It allows you to wait until the process finishes.
    Put this code in a Module (Module1.bas):

    Code:
    option Explicit
        
    '//public Constants
    public Const NORMAL_PRIORITY_CLASS = &H20&
    public Const INFINITE = -1&
        
    '//public Types
    public Type STARTUPINFO
       cb as Long
       lpReserved as string
       lpDesktop as string
       lpTitle as string
       dwX as Long
       dwY as Long
       dwXSize as Long
       dwYSize as Long
       dwXCountChars as Long
       dwYCountChars as Long
       dwFillAttribute as Long
       dwFlags as Long
       wShowWindow as Integer
       cbReserved2 as Integer
       lpReserved2 as Long
       hStdInput as Long
       hStdOutput as Long
       hStdError as Long
    End Type
        
    public Type PROCESS_INFORMATION
       hProcess as Long
       hThread as Long
       dwProcessID as Long
       dwThreadID as Long
    End Type
        
    '//API Declarations
    public Declare Function WaitForSingleObject Lib "kernel32" (byval _
       hHandle as Long, byval dwMilliseconds as Long) as Long
        
    public Declare Function CreateProcessA Lib "kernel32" (byval _
       lpApplicationName as Long, byval lpCommandLine as string, byval _
       lpProcessAttributes as Long, byval lpThreadAttributes as Long, _
       byval bInheritHandles as Long, byval dwCreationFlags as Long, _
       byval lpEnvironment as Long, byval lpCurrentDirectory as Long, _
       lpStartupInfo as STARTUPINFO, lpProcessInformation as _
       PROCESS_INFORMATION) as Long
        
    public Declare Function CloseHandle Lib "kernel32" (byval _
       hObject as Long) as Long
    
    
    
        
    Put This Code In A Form (Form1):
    
    private Sub Command1_Click()
        Dim AppToRun as string
        Dim ParamForApp as string
        Dim CmdLine as string
           
        '//set Application to Run
        AppToRun = "C:\WINNT\System32\CMD.exe"
           
        '//set Command Line Parameters
        '//The "/C" Tells Windows to Run The Command then Terminate
        '//The Command Line (CMD.exe)
        ParamForApp = " /C MD New_Folder" '//Make new Directory Called 'New_Folder'
           
        '//Build Command string
        CmdLine = AppToRun & ParamForApp
           
        '//Shell App And Wait for It to Finish
        ExecCmd CmdLine
               
    End Sub
        
    public Sub ExecCmd(CmdLine as string)
        Dim Proc as PROCESS_INFORMATION
        Dim start as STARTUPINFO
        Dim ReturnValue as Integer
           
        '//Initialize The STARTUPINFO Structure
        start.cb = len(start)
           
        '//Start The Shelled Application
        ReturnValue = CreateProcessA(0&, CmdLine, 0&, 0&, 1&, _
           NORMAL_PRIORITY_CLASS, 0&, 0&, start, Proc)
           
        '//Wait for The Shelled Application to Finish
        Do
           ReturnValue = WaitForSingleObject(Proc.hProcess, 0)
           DoEvents
        Loop Until ReturnValue <> 258
           
        '//Close Handle to Shelled Application
        ReturnValue = CloseHandle(Proc.hProcess)
           
    End Sub


    Kris
    Software Engineer
    Phoenix,AZ
    Last edited by Cimperiali; October 31st, 2004 at 04:41 PM. Reason: substitute html chars for "<" and ">"
    Kris
    Software Engineer
    Phoenix, AZ USA

  5. #5
    Join Date
    Jul 2000
    Location
    Milano, Italy
    Posts
    7,726

    Great!

    Man, this is great. I am only sorry I do not to have any more points to rate...
    Hope someone else will do.
    Have a nice day,
    Cesare


    Special thanks to Lothar "the Great" Haensler, Tom Archer, Chris Eastwood, TCartwright, Bruno Paris, Dr_Michael
    and all the other wonderful people who made and make Codeguru a great place.
    Come back soon, you Gurus.

    The Rater
    ...at present time, using mainly Net 4.0, Vs 2010



    Special thanks to Lothar "the Great" Haensler, Chris Eastwood , dr_Michael, ClearCode, Iouri and
    all the other wonderful people who made and make Codeguru a great place.
    Come back soon, you Gurus.

  6. #6
    Join Date
    Mar 2000
    Location
    Arizona, USA
    Posts
    493

    Re: Great!

    Thanks!!! I have received a lot of help from this board so
    if I can help someone else, that is all that matters!

    Have a great day!

    Kris
    Software Engineer
    Phoenix,AZ
    Kris
    Software Engineer
    Phoenix, AZ USA

  7. #7
    Join Date
    Jul 2000
    Location
    Milano, Italy
    Posts
    7,726

    Merging some jobs...

    ...a small example...
    'credits should go to Mksa and Softweng, and -yes- a bit to M$ also...
    Attached Files Attached Files
    ...at present time, using mainly Net 4.0, Vs 2010



    Special thanks to Lothar "the Great" Haensler, Chris Eastwood , dr_Michael, ClearCode, Iouri and
    all the other wonderful people who made and make Codeguru a great place.
    Come back soon, you Gurus.

  8. #8
    Join Date
    Jan 2002
    Location
    Quebec/Canada
    Posts
    124
    I worked with this ExecCmd code before, I like it because it will wait until the dos command is done to return.

    I made some verry small modification to it so i can choose to show or not the dos window to the user :

    In the declaration section :
    Private Const STARTF_USESHOWWINDOW = 1
    Private Const SW_HIDE = 0

    Replaced the ExecCmd declare function with :
    Public Function ExecCmd(ByVal cmdline as String, Optional ByVal HideWindow As Boolean = False) As Long

    And added the following code at the start of the function :
    If (HideWindow) Then
    start.dwFlags = STARTF_USESHOWWINDOW
    start.wShowWindow = SW_HIDE
    End If
    start.cb = Len(start)

    It works verry well except in some case like when the dos window wait for a user input and the function never return until the process is killed.

    Just my 2
    Last edited by Heulsay; August 25th, 2003 at 01:21 PM.

  9. #9
    Join Date
    Jun 2004
    Posts
    2

    How to retrieve application program return message

    Hi Buddy,
    I am trying to run a application (abc.exe) program from VB code using SHELL command.
    Anybody knows how to retrieve the application program error message.

    If I use SHELL.EXEC command it's working but the DOS window shows up which I don't like.

    Please help me.

  10. #10
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808
    Don't know whether anybody will c this...

    Can't we do it this way... i think it is a bit simple and just two lines of code...

    Code:
    Private Sub Command1_Click()
    Dim sCommand As String
    sCommand = "md C:\myDir"
    Shell ("cmd.exe /c" & sCommand)
    
    End Sub
    I don't know if this is the perfect way to do it...but it seems to work for me...
    Last edited by vb_the_best; June 2nd, 2005 at 03:02 AM.

  11. #11
    Join Date
    Nov 1999
    Location
    Bangalore, India
    Posts
    31

    Another related help needed

    Hi All!

    This helped me a lot. Now I am creating ASCII reports from VB (I have written a ReportWriter Class and using FSO). I print them on the DMP's over the network or the local printer using the DOS command "type {filename} > PRN" or something like "type {filename} > \\MAC6\Epson". This is of immense help.

    But recently I got a problem. The printer is not a DMP but a Laser printer. I tried with Laser Printers connected on LPT and it worked fine. But here the Printer is connected on USB and my technique ...F A I L E D.

    Anybody can give me some advice?

    Thanks in advance,

    Regards,

    Kangkan

  12. #12
    Join Date
    Jun 2005
    Posts
    2

    Re: how can we run a dos command from VB

    Hi!

    Thank's for the help to run Dos commands! I'm running a bat file with mine app. But how can I read variables from two textboxes so they will be added to the dos command: CmdLine = AppToRun & ParamForApp & Text1 & Text2

    And even better, could I get the value for textbox1 from a html tag in a Webbrowser component in my frame window?


    I use the code that I found here:

    Option Strict Off
    Option Explicit On
    Friend Class FrmLaunchDos
    Inherits System.Windows.Forms.Form
    Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer)

    Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click
    '//set Application to Run
    ' AppToRun = "C:\WINNT\System32\CMD.exe"

    Dim AppToRun As String
    Dim ParamForApp As String
    Dim CmdLine As String
    Select Case getVersion()
    Case "Windows 95", "Windows 98", "Windows Millennium"
    AppToRun = "Command.exe"
    Case "Windows NT 3.51", "Windows NT 4.0", "Windows 2000", "Windows XP"
    AppToRun = "Cmd.exe"
    Case "Failed"
    MsgBox("Unable to determine Os type")
    Exit Sub
    End Select



    '//set Command Line Parameters
    '//The "/C" Tells Windows to Run The Command then Terminate
    '//The Command Line (CMD.exe)
    'ParamForApp = " /C MD New_Folder" '//Make new Directory Called 'New_Folder'
    'use /C to launch command without see windwow
    'use /K to see output
    ParamForApp = " /K ..\resources\test.bat"

    '//Build Command string
    CmdLine = AppToRun & ParamForApp
    '//Shell App And Wait for It to Finish
    ExecCmd(CmdLine)
    End Sub
    Private Sub ExecCmd(ByRef CmdLine As String)
    Dim Proc As PROCESS_INFORMATION
    Dim start As STARTUPINFO
    Dim ReturnValue As Short

    '//Initialize The STARTUPINFO Structure
    start.cb = Len(start)

    start.wShowWindow = 1 'SW_NORMAL = 1; SW_MAXIMIZE = 3


    '//Start The Shelled Application
    ReturnValue = CreateProcessA(0, CmdLine, 0, 0, 1, NORMAL_PRIORITY_CLASS, 0, 0, start, Proc)

    '//Wait for The Shelled Application to Finish
    Do
    ReturnValue = WaitForSingleObject(Proc.hProcess, 0)
    System.Windows.Forms.Application.DoEvents()
    Loop Until ReturnValue <> 258

    '//Close Handle to Shelled Application
    ReturnValue = CloseHandle(Proc.hProcess)

    End Sub

    Private Sub FrmLaunchDos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub


    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim Text1 As String
    End Sub

    Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
    Dim Text2 As String
    End Sub
    End Class

  13. #13
    Join Date
    Oct 2001
    Location
    Melbourne, Australia
    Posts
    576

    Re: how can we run a dos command from VB

    Quote Originally Posted by papa_6
    Thank's for the help to run Dos commands! I'm running a bat file with mine app. But how can I read variables from two textboxes so they will be added to the dos command: CmdLine = AppToRun & ParamForApp & Text1 & Text2
    I am guessing you are asking how to access the command line arg from the batch file? if so, do this:

    1. create a batch file (i.e. test.bat)
    2. add the following lines to it:
    Code:
    echo off
    echo %1
    echo %2
    3. run the batch file from a command line by typing "test.bat hello world"

    the program will output
    hello
    world
    so, as you may figure from the above example, %1 is the first arg, %2 the second, seperated by spaces. pretty simple. (btw, if you don't know, echo is the command to print to the screen, and echo off tells he OS not to print the commands before it does the command. take out the line "echo off" and you will get output like this:
    C:\echo hello
    hello

    C:\echo world
    world

  14. #14
    Join Date
    Jun 2005
    Posts
    2

    Re: how can we run a dos command from VB

    Thank's for Your response!

    I maybe explained my problem badly... I'm using %1 and %2 in my bat already, but how can I get the values that the user fills in to the two textboxes to the batch file?

    1. The user fills in for example his Name in textbox1 and a number that appears in my forms webpage in textbox2.

    2. Then the user presses the Command1 and the batch program is starting. At this point I want the content from the two textboxes to go with the batch command so they becomes %1 and %2 values in it.

  15. #15
    Join Date
    Aug 2002
    Location
    Dubai
    Posts
    1,183

    Re: how can we run a dos command from VB

    Why not create batch files on the fly. Get the values entered by the user format the string for the batch file using the required commands and the values of the input write this to disk as mybatchfile.bat and then run mybatchfile.bat

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center