Results 1 to 40 of 59

Threaded View

  1. #1

    Thread Starter
    "The" RedHeadedLefty
    Join Date
    Aug 2005
    College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation

    Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]

    The following code is a sample of how you can automate the command prompt window. It creates a new process in a thread with "cmd" as the filename (which starts a new command prompt window). A thread was used (although not required) as a preventative measure just in case the CMD window would hang for some reason. If it hangs and it is not started on a thread, then your application would hang as well until the cmd window was closed or killed.

    The Process.StartInfo property contains a .RedirectStandardInput and .RedirectStandardOutput property that allows you to redirect the input and output associated with the process. The StandardOutput and StandardInput properties of the Process class are streamreaders and streamwriters, respectively, which you can set in order to send and receive the data.

    The code below simply runs a command that is listed in a textbox, and outputs the results into a textbox. The entire project file is included below in the attachments.

    EDIT - The original example below has a problem in the threading. See the 2005 example code in post 10 that corrects this issue
    VB Code:
    1. Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
    2.         Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
    3.         CMDThread.Start()
    4. End Sub
    5. Private Sub CMDAutomate()
    6.         Dim myprocess As New Process
    7.         Dim StartInfo As New System.Diagnostics.ProcessStartInfo
    8.         StartInfo.FileName = "cmd" 'starts cmd window
    9.         StartInfo.RedirectStandardInput = True
    10.         StartInfo.RedirectStandardOutput = True
    11.         StartInfo.UseShellExecute = False 'required to redirect
    12.         myprocess.StartInfo = StartInfo
    13.         myprocess.Start()
    14.         Dim SR As System.IO.StreamReader = myprocess.StandardOutput
    15.         Dim SW As System.IO.StreamWriter = myprocess.StandardInput
    16.         SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
    17.         SW.WriteLine("exit") 'exits command prompt window
    18.         txtResults.Text = SR.ReadToEnd 'returns results of the command window
    19.         SW.Close()
    20.         SR.Close()
    21. End Sub
    Attached Images Attached Images  
    Attached Files Attached Files
    Last edited by gigemboy; Sep 12th, 2006 at 12:51 PM.

Posting Permissions

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


Click Here to Expand Forum to Full Width