Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]-VBForums
Page 1 of 2 12 LastLast
Results 1 to 40 of 57

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

  1. #1

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

    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 01:51 PM.

  2. #2
    Super Moderator RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,152

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    Very nice example Gigemboy!
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Star Wars Gangsta Rap Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel Core 2 Extreme Ed., 2 WD Raptor 10K RPM 300 GB HDs, 2 GBs DDR2 667 MHz RAM, 2 Viewsonic 24" LCDs, Windows 7 SP-1/Windows 8.1, Office 2010, VS 2013

  3. #3
    Member
    Join Date
    Feb 2006
    Posts
    35

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    I get an "InvalidOperationException"...

  4. #4

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

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    The below code adds one line, with the "CreateNoWindow" property of the StartInfo object set to "True", this way the command window doesnt open up at all... (Thanks to jmcilhinney)
    VB Code:
    1. Dim myprocess As New Process
    2.         Dim StartInfo As New System.Diagnostics.ProcessStartInfo
    3.         StartInfo.FileName = "cmd" 'starts cmd window
    4.         StartInfo.RedirectStandardInput = True
    5.         StartInfo.RedirectStandardOutput = True
    6.         StartInfo.UseShellExecute = False 'required to redirect
    7.         StartInfo.CreateNoWindow = True '<---- creates no window, obviously
    8.         myprocess.StartInfo = StartInfo
    9.         myprocess.Start()
    10.         Dim SR As System.IO.StreamReader = myprocess.StandardOutput
    11.         Dim SW As System.IO.StreamWriter = myprocess.StandardInput
    12.         SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
    13.         SW.WriteLine("exit") 'exits command prompt window
    14.         txtResults.Text = SR.ReadToEnd 'returns results of the command window
    15.         SW.Close()
    16.         SR.Close()

  5. #5
    New Member
    Join Date
    Mar 2006
    Posts
    1

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    Hi!

    Is there a way to execute this on a remote computer, like PSExec from SysInternals?

    I need to execute a "CMD" on a remote machine and redirect the input/output to my console.

    I know PSExec can do that but I want it my way

    Thanks.

  6. #6

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

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    I know its been a while since this post, but I will go ahead and reply with "I do not know of a way to do that" (which probably was assumed since no replies). This code just shows how to automate the prompt on your local machine.

  7. #7
    New Member
    Join Date
    Jul 2006
    Posts
    2

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    Hello,

    Can you please help me understand how can I take output without exiting the process. It seems this sample (posted on many sites ) returns the input to the input stream only when the process exits. Is there anyway we can make a communication.

    I need to do the following for using a public library:

    Send in one command to command prompt based exe.
    Read its output from the command prompt.
    Without terminating i have to send another command based on previous output and read output again.
    I have to do this iteratively.

    Will be glad if you can help out.
    Regards,

  8. #8
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,602

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    I downloaded the project files (CmdRedirect.zip) in your original post & ran it in VB2005 Express & I get the following error:

    Cross-thread operation not valid: Control 'txtResults' accessed from a thread other than the thread it was created on.

    What do I need to do to fix this? Thanks...

  9. #9

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

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    Yeah I noticed that a long time ago, just haven't updated the code. Its because in that code it is trying to update a control directly from within the thread, which is a no-no. In 2003 you can get away with it sometimes, but in 2005 you can't. You can try running the code without using a thread, it should still work, but the form will hang until the process is complete. It would need to be changed to do "correct" threading, either using a background worker or manually by invoking a delegate in the thread to update the text. I'll post the updated code when I get around to it
    Last edited by gigemboy; Sep 12th, 2006 at 01:16 PM.

  10. #10

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

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    Here is the updated code, with a delegate used to update the text. Tested in 2005 and the code worked fine. There is an attachment of the new 2005 project example at the end of the post as well.
    VB Code:
    1. 'Form code from sample project
    2.  
    3.     Private Results As String
    4.     Private Delegate Sub delUpdate()
    5.     Private Finished As New delUpdate(AddressOf UpdateText)
    6.  
    7.     Private Sub UpdateText()
    8.         txtResults.Text = Results
    9.     End Sub
    10.  
    11.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    12.         Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
    13.         CMDThread.Start()
    14.     End Sub
    15.  
    16.     Private Sub CMDAutomate()
    17.         Dim myprocess As New Process
    18.         Dim StartInfo As New System.Diagnostics.ProcessStartInfo
    19.         StartInfo.FileName = "cmd" 'starts cmd window
    20.         StartInfo.RedirectStandardInput = True
    21.         StartInfo.RedirectStandardOutput = True
    22.         StartInfo.UseShellExecute = False 'required to redirect
    23.         StartInfo.CreateNoWindow = True 'creates no cmd window
    24.         myprocess.StartInfo = StartInfo
    25.         myprocess.Start()
    26.         Dim SR As System.IO.StreamReader = myprocess.StandardOutput
    27.         Dim SW As System.IO.StreamWriter = myprocess.StandardInput
    28.         SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
    29.         SW.WriteLine("exit") 'exits command prompt window
    30.         Results = SR.ReadToEnd 'returns results of the command window
    31.         SW.Close()
    32.         SR.Close()
    33.         'invokes Finished delegate, which updates textbox with the results text
    34.         Invoke(Finished)
    35.     End Sub
    Attached Files Attached Files
    Last edited by gigemboy; Sep 12th, 2006 at 01:46 PM.

  11. #11
    Fanatic Member uniquegodwin's Avatar
    Join Date
    Jul 2005
    Location
    Chennai,India
    Posts
    693

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

    Hi bud,
    I made some more changes or updates..
    I made it synchronous to the commands running on the command prompt so theres no delay for it to come on the rich text box.
    The command prompt doesnt exit everytime now..
    Thats all..
    Hope it helps
    Take a look..Ive attached it.
    Thanks
    Attached Files Attached Files
    Godwin

    Help someone else with what someone helped you!

  12. #12

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

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

    After typing a few commands, your "edited" example doesn't work anymore... it hangs up and no results are shown in the box...

  13. #13
    Junior Member w8taminute's Avatar
    Join Date
    Aug 2006
    Posts
    24

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

    How would I get the command prompt to open in my parent form?

  14. #14
    Hyperactive Member TTn's Avatar
    Join Date
    Jul 2004
    Posts
    464

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

    I changed this a bit, but the main thing wrong was the "results of the command window".


    Code:
       Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim CMDThread As New Threading.Thread(AddressOf CMDAutomateThread)
            CMDThread.Start()
        End Sub
        Private Sub CMDAutomateThread()
            TextBox1.Text = CMDAutomate("date", "12/31/2099") 'Set textbox to string return
        End Sub
    
        Private Function CMDAutomate(ByVal cmdString As String, ByVal cmdString2 As String) As String
            Dim myprocess As New Process
            Dim StartInfo As New System.Diagnostics.ProcessStartInfo
            Dim s As String = ""
            StartInfo.FileName = "cmd" 'starts cmd window        
            StartInfo.RedirectStandardInput = True
            StartInfo.RedirectStandardOutput = True
            StartInfo.UseShellExecute = False 'required to redirect    
            ' StartInfo.CreateNoWindow = True 'creates no cmd window         
            myprocess.StartInfo = StartInfo
            myprocess.Start()
            Dim SR As System.IO.StreamReader = myprocess.StandardOutput
            Dim SW As System.IO.StreamWriter = myprocess.StandardInput
            SW.WriteLine(cmdString) 'the commands you wish to run.....      
            SW.WriteLine(cmdString2)
            s = SR.ReadToEnd 'returns results of the command window  before exit
            SW.WriteLine("exit") 'exits command prompt window      
            SW.Close()
            SR.Close()
            Return s
        End Function
    Thanks for the example!

  15. #15
    Member
    Join Date
    Jul 2007
    Location
    Silly Clone Valley CA
    Posts
    47

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

    Quote Originally Posted by TTn
    I changed this a bit, but the main thing wrong was the "results of the command window".


    Code:
       Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim CMDThread As New Threading.Thread(AddressOf CMDAutomateThread)
            CMDThread.Start()
        End Sub
        Private Sub CMDAutomateThread()
            TextBox1.Text = CMDAutomate("date", "12/31/2099") 'Set textbox to string return
        End Sub
    
        Private Function CMDAutomate(ByVal cmdString As String, ByVal cmdString2 As String) As String
            Dim myprocess As New Process
            Dim StartInfo As New System.Diagnostics.ProcessStartInfo
            Dim s As String = ""
            StartInfo.FileName = "cmd" 'starts cmd window        
            StartInfo.RedirectStandardInput = True
            StartInfo.RedirectStandardOutput = True
            StartInfo.UseShellExecute = False 'required to redirect    
            ' StartInfo.CreateNoWindow = True 'creates no cmd window         
            myprocess.StartInfo = StartInfo
            myprocess.Start()
            Dim SR As System.IO.StreamReader = myprocess.StandardOutput
            Dim SW As System.IO.StreamWriter = myprocess.StandardInput
            SW.WriteLine(cmdString) 'the commands you wish to run.....      
            SW.WriteLine(cmdString2)
            s = SR.ReadToEnd 'returns results of the command window  before exit
            SW.WriteLine("exit") 'exits command prompt window      
            SW.Close()
            SR.Close()
            Return s
        End Function
    Thanks for the example!
    DO NOT TRY THIS CODE! It will change your system date. Yeah, maybe I'm an idiot for not knowing that "date 12/31/2099" is the command to set your system to the year 2099, but still, just warning people out there.

  16. #16
    Hyperactive Member TTn's Avatar
    Join Date
    Jul 2004
    Posts
    464

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

    SlumberMachine,

    Yeah maybe you are.
    Usually everyone would look at the code to see what it means, and so yeah it's a no-brainer. There are comments throughout it.
    I don't appreciate you posting things like:
    "DONT TRY TTN'S MALICIOUS CODE".

    By all means, everyone can try my/gigemboy's code, with the command you want, in the window.
    Duh.

  17. #17
    Member
    Join Date
    Jul 2007
    Location
    Silly Clone Valley CA
    Posts
    47

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

    Quote Originally Posted by TTn
    SlumberMachine,

    Yeah maybe you are.
    Usually everyone would look at the code to see what it means, and so yeah it's a no-brainer. There are comments throughout it.
    I don't appreciate you posting things like:
    "DONT TRY TTN'S MALICIOUS CODE".

    By all means, everyone can try my/gigemboy's code, with the command you want, in the window.
    Duh.
    Look, I didn't mean to hurt your feelings, but what you posted was not only wrong, but malicious, and you know it. And I'm just trying to do what is right and warn people, like myself that are trying to learn. You didn't comment that line of the code. If you didn't intend for it to be malicious then why not do a "dir c:" instead? I've never heard or ever had to use a date command in dos and just figured it would return something interesting like the number of days until that date or something. Don't get defensive, just do what is right for others and admit the mistake and accept the punishment (which is someone else warning others not to use a bit of code).

    No need to take it all personal or anything, and if you want to think that I'm an ignorant idiot, that doesn't know crap about dos commands or vb that is fine with me. It sounds like you have an awesome wealth of knowledge in this area and I'm sure you are way better then me. but.. the fact is:

    you posted dangerous code, which did screw up someones system, and others should be warned to not make the same mistake when trying it out.

  18. #18
    Hyperactive Member TTn's Avatar
    Join Date
    Jul 2004
    Posts
    464

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

    You could have, and should have simply stated that the command, will adjust your clock.
    If anyone intends to use the command window, then they'd be putting in their own command. Your point is completely mute, because everyone knows that.

    I did comment that piece in fact.
    "'the commands you wish to run..... "

    That's not malicious, because you could enter any command you like.
    I can't think of one thing that can be maliciously affected, by changing the time anyway. It didn't happen, you can just change the time back. Woopie. No systems were screwed up, as you implied, and lied about.

    I hate liars, that try to make a point by testifying false data.
    I really wish the moderators would ban counter-productive members like you.

  19. #19
    Member
    Join Date
    Jul 2007
    Location
    Silly Clone Valley CA
    Posts
    47

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

    These are the facts:

    It did screw up someones computer (mine) and took a few hours, after setting the date back to the correct time to repair the damage which included:

    Outlook Calender - had to have all appointments reset since they all expired.
    VB Express 2005 - All projects would not compile and would use the last compile since the date change.
    Trend Micro Client server security agent failed to run until I reinstalled.

    As for lying, this code here:

    Code:
      Private Sub CMDAutomateThread()
            TextBox1.Text = CMDAutomate("date", "12/31/2099") 'Set textbox to string return
        End Sub
    Does not have any comment that states what those commands do.

    If you weren't so set on judging your self worth by your reputation on an internet forum you could save a lot of counter production here. It's funny how you get so defensive over this whole thing. You just need to chill and stop caring so much about what others think of you and your knowledge of computers.

    I'm not going to check this thread anymore, best of luck to you.

  20. #20
    Hyperactive Member TTn's Avatar
    Join Date
    Jul 2004
    Posts
    464

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

    That line sets the textbox contents, to the return value of the function.
    It seems you don't know what a function is, otherwise you would have realized where to find this comment within it:

    "'the commands you wish to run..... "
    Since you didn't wish to run my date command example, then it was your mistake. Almost all examples have a spot, where you put the custom parameter that you want. The place to put this customization was clearly marked, but you probably glanced over it without thinking or understanding.

  21. #21
    New Member
    Join Date
    Jul 2008
    Posts
    1

    Re: Automate Command Prompt Window (CMD), Redirect Output to Application

    Quote Originally Posted by gigemboy
    Here is the updated code, with a delegate used to update the text. Tested in 2005 and the code worked fine. There is an attachment of the new 2005 project example at the end of the post as well.
    VB Code:
    1. 'Form code from sample project
    2.  
    3.     Private Results As String
    4.     Private Delegate Sub delUpdate()
    5.     Private Finished As New delUpdate(AddressOf UpdateText)
    6.  
    7.     Private Sub UpdateText()
    8.         txtResults.Text = Results
    9.     End Sub
    10.  
    11.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    12.         Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
    13.         CMDThread.Start()
    14.     End Sub
    15.  
    16.     Private Sub CMDAutomate()
    17.         Dim myprocess As New Process
    18.         Dim StartInfo As New System.Diagnostics.ProcessStartInfo
    19.         StartInfo.FileName = "cmd" 'starts cmd window
    20.         StartInfo.RedirectStandardInput = True
    21.         StartInfo.RedirectStandardOutput = True
    22.         StartInfo.UseShellExecute = False 'required to redirect
    23.         StartInfo.CreateNoWindow = True 'creates no cmd window
    24.         myprocess.StartInfo = StartInfo
    25.         myprocess.Start()
    26.         Dim SR As System.IO.StreamReader = myprocess.StandardOutput
    27.         Dim SW As System.IO.StreamWriter = myprocess.StandardInput
    28.         SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
    29.         SW.WriteLine("exit") 'exits command prompt window
    30.         Results = SR.ReadToEnd 'returns results of the command window
    31.         SW.Close()
    32.         SR.Close()
    33.         'invokes Finished delegate, which updates textbox with the results text
    34.         Invoke(Finished)
    35.     End Sub
    I executed the code provided, with the following command:
    gpg --verify "C:\Documents and Settings\Javier\Escritorio\UDP2006\Semestre5\Negocios en Internet\Catalogo de la tienda\comando correcto.txt.asc"

    I get the following output in the textbox:
    Microsoft Windows XP [Versi˘n 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.

    C:\Documents and Settings\Javier\Escritorio\UDP2006\Semestre5\Negocios en Internet\2005CMDExample\2005CMDExample\2005CMDExample\bin\Release>gpg --verify "C:\Documents and Settings\Javier\Escritorio\UDP2006\Semestre5\Negocios en Internet\Catalogo de la tienda\comando correcto.txt.asc"

    C:\Documents and Settings\Javier\Escritorio\UDP2006\Semestre5\Negocios en Internet\2005CMDExample\2005CMDExample\2005CMDExample\bin\Release>exit
    But if I enter the same string, manually, at the cmd console, I get the following (and desired) output:

    Microsoft Windows XP [Versión 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.

    C:\Documents and Settings\Javier>gpg --verify "C:\Documents and Settings\Javier
    \Escritorio\UDP2006\Semestre5\Negocios en Internet\Catalogo de la tienda\comando
    correcto.txt.asc"
    gpg: Firmado el 07/08/08 22:24:37
    gpg: usando RSA clave 0xE89F63D4
    gpg: Firma correcta de "Faramir_cl <faramir0cl@gmail.com>"

    C:\Documents and Settings\Javier>
    This last output (the one I get if I enter the command manually) is what I need... how can I get VB to let me do that?

    I need to make this work... and I am running out of time...

  22. #22
    Junior Member
    Join Date
    Jan 2009
    Posts
    31

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

    This is one of the most useful pieces of code I have come across in the Codebank.

    A quick question: The code in post #10 always clears the TextBox first, then updates it with the results of the next command. How could this 'clear first' be inhibited, so the TextBox shows continuous output, as a normal cmd would do?

  23. #23
    Hyperactive Member TTn's Avatar
    Join Date
    Jul 2004
    Posts
    464

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

    This is one of the most useful pieces of code I have come across in the Codebank.

    A quick question: The code in post #10 always clears the TextBox first, then updates it with the results of the next command. How could this 'clear first' be inhibited, so the TextBox shows continuous output, as a normal cmd would do?
    Post #10 has an error, because it exits prematurely, before reading the content. Take a quick look at post #14, but run your own command.

    Do you want the window not to exit? You don't have to command the exit.
    How many commands do you wish to run?

    You could append the textbox after each command, by doing something like this:
    Code:
    SW.WriteLine("A command here")
    TextBox1.Text &= SR.ReadToEnd
    SW.WriteLine("Another command here")
    TextBox1.Text &= SR.ReadToEnd

  24. #24
    Junior Member
    Join Date
    Jan 2009
    Posts
    31

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

    I solved the clear first problem by changing:

    Code:
    Private Sub CMDAutomateThread()
            txtResults.Text = Results
        End Sub
    to

    Code:
    Private Sub UpdateText()
            txtResults.AppendText(Results)
            txtResults.SelectionStart = txtResults.Text.Length ' this line and the next
            txtResults.ScrollToCaret() 'sets the scrollbar to the bottom
        End Sub
    I also wanted to see the latest data in the textbox, and scroll back to see older data, hence the other two lines of code.

    I do not want the cmd window to close, I want it, and 5 others, to stay open. I am adapting this code to open 6 server windows (cmd-like) as part of a GUI for a Virtual World (here is the work-in-progress)

    My textboxes should act in the same way as these server (cmd console) windows, i.e. I can see all status messages, and I can enter commands and see the results.

    While testing, I will send commands in the way the code in this thread uses, but later I will change it to specific commands behind button clicks, or Menu options.

    I am currently working on a way to set a rolling buffer size for the TextBox, so it does not get too big.

    Your alternative code in post #14 looks very interesting indeed. I will have a play with that tomorrow.

    Rock

  25. #25
    Junior Member
    Join Date
    Jan 2009
    Posts
    31

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

    I am a little bit confused about the purpose of the following line in the code:

    SW.Writeline("exit")

    What is this line for? The comment says 'exits command prompt window, but does this mean that the cmd window is now closed, or what?

    What I need is for the cmd window to remain open at all times, displaying its messages in my TextBox, accepting and executing commands, and displaying the results, until I close the application.

    What do I need to do to the code to achieve this?

    TIA

    Rock

  26. #26
    Hyperactive Member Cyb3rH4Xter's Avatar
    Join Date
    May 2009
    Location
    Sweden
    Posts
    449

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

    @Rock Vacirca
    Remove that line to have the cmd window open.

    I want to use this code to make a better console for my cs server.
    The cs server can't be run with the DEP (Data Execution Protection), so i have disabled the dep for the file. When i run it from my shortcut on the desktop the server runs fine, starts a cmd-like window. But when i run it via your code, it runs with DEP, can i disable DEP in the .StartInfo or?
    But when i change the .filename to the path to the file (hlds.exe)

  27. #27
    Banned
    Join Date
    Jun 2009
    Posts
    12

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

    is this to control cmd ??

  28. #28
    New Member
    Join Date
    Jun 2011
    Posts
    1

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

    Quote Originally Posted by Cyb3rH4Xter View Post
    @Rock Vacirca
    Remove that line to have the cmd window open.

    I want to use this code to make a better console for my cs server.
    The cs server can't be run with the DEP (Data Execution Protection), so i have disabled the dep for the file. When i run it from my shortcut on the desktop the server runs fine, starts a cmd-like window. But when i run it via your code, it runs with DEP, can i disable DEP in the .StartInfo or?
    But when i change the .filename to the path to the file (hlds.exe)
    To disable DEP, you can use this command in the cmd prompt... or enter in this app and it will load just the same.

    Code:
    bcdedit.exe /set {current} nx AlwaysOff
    You should only need to disable DEP once... so no need to disable every time you load app.... therefor no need to input this into source.

    Reboot PC once you've run the above code... your done.

    By the way, this is a great thread... nice code, will make good use of it one day.

    HTK

  29. #29
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 2005
    Location
    Montana
    Posts
    2,901

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

    My application freezes everytime I try to read the output, any ideas?

    Code:
    Private Function GetChannelStatus(ByVal channelName As String) As String
    
        Dim StartInfo As New System.Diagnostics.ProcessStartInfo("C:\Program Files\IBM\WebSphere MQ\bin\runmqsc.exe")
    
        StartInfo.RedirectStandardInput = True
        StartInfo.RedirectStandardOutput = True
        StartInfo.UseShellExecute = False 'required to redirect
        StartInfo.CreateNoWindow = True 'creates no cmd window
    
        Dim myprocess = Process.Start(StartInfo)
    
        Dim results = ""
    
        Dim SR As System.IO.StreamReader = myprocess.StandardOutput
        Dim SW As System.IO.StreamWriter = myprocess.StandardInput
        SW.WriteLine(String.Format("DISPLAY CHSTATUS({0})", channelName))
        System.Windows.Forms.MessageBox.Show("here1")
        results = SR.ReadToEnd 'returns results of the command window
        System.Windows.Forms.MessageBox.Show("here2")
        SW.WriteLine("end")
        SW.Close()
        SR.Close()
    
        Dim statusExpression As New Regex("(?<=STATUS\()\w+(?=\))")
        Return statusExpression.Match(results).Value
    
    End Function
    That is the very essence of human beings and our very unique capability to perform complex reasoning and actually use our perception to further our understanding of things. We like to solve problems. -Kleinma

    Does your code in post #46 look like my code in #45? No, it doesn't. Therefore, wrong is how it looks. - jmcilhinney

  30. #30
    Lively Member
    Join Date
    Dec 2006
    Posts
    75

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

    Hey, thank you very much for the code but i am having a problem.
    I want to send a CTRL-C event to the DOS app, since it's the only way to
    interrupt it.
    I tried to send a CTRL-C event using the "ConsoleCtrlEvent" API, with no
    success. I tried both :

    **** Const CTRL_C_EVENT As Integer = 0
    Const CTRL_BREAK_EVENT As Integer = 1

    <DllImport("kernel32.dll")> _
    Private Shared Function GenerateConsoleCtrlEvent(ByVal dwCtrlEvent As Integer, ByVal dwProcessGroupId As Integer) As Boolean
    End Function ****

    GenerateConsoleCtrlEvent(ConsoleCtrlEvent.CTRL_C, 0)
    and
    GenerateConsoleCtrlEvent(ConsoleCtrlEvent.CTRL_C, myprocess.id)
    But none of them seems to work.

    So if someone can help me, I'd be very grateful.
    Thank you in advance !

  31. #31
    New Member
    Join Date
    Aug 2008
    Posts
    3

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

    Old thread however I love the code except for the fact that one part is just not working for me. When I execute this the cmd window sticks and nothing happens till I close the cmd window then it continues. For the life of me I can not figure out how to get past this.

    Code:
    Private Sub NDS_Start_SIT_Logic()
            Dim NDS_Start_SIT_Putty_Command_Value As String = "C:\plink.exe " + Unix_User_Name + "@spongeshrimp.grhq.XXX.com -pw " + Unix_User_Password
            Dim myprocess As New Process
            Dim StartInfo As New System.Diagnostics.ProcessStartInfo()
            StartInfo.FileName = "cmd.exe"
            StartInfo.RedirectStandardInput = True
            StartInfo.RedirectStandardOutput = True
            StartInfo.UseShellExecute = False
            StartInfo.CreateNoWindow = False 'creates no cmd window
            myprocess.StartInfo = StartInfo
            myprocess.Start()
            Dim SR As System.IO.StreamReader = myprocess.StandardOutput
            Dim SW As System.IO.StreamWriter = myprocess.StandardInput
            SW.WriteLine(NDS_Start_SIT_Putty_Command_Value)
            SW.WriteLine("ps -ef | grep nds")
            SW.WriteLine("exit")
            Results = SR.ReadToEnd
            SW.Close()
            SR.Close()
            Invoke(NDS_Start_SIT_Updater)
        End Sub

    The line that it sticks on is the SR.ReadToEnd.
    Code:
    Results = SR.ReadToEnd
    Again like I said the code works but it can not seem to get past the ReadToEnd till you X out of the cmd window.

    Does anyone know how to correct this? Thanks!

  32. #32
    Junior Member
    Join Date
    Apr 2012
    Posts
    20

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

    ok im running vb 10 i tried using the code and it still doesnt work for me it just comes up as blank on the results am i doing something wronge?

  33. #33
    New Member
    Join Date
    Apr 2012
    Posts
    2

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

    Quote Originally Posted by tekatsu View Post
    ok im running vb 10 i tried using the code and it still doesnt work for me it just comes up as blank on the results am i doing something wronge?
    I am interested in this as well. Is there updates to the code to work in VB10?

  34. #34
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,191

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

    Quote Originally Posted by tekatsu View Post
    ok im running vb 10 i tried using the code and it still doesnt work for me it just comes up as blank on the results am i doing something wronge?
    Quote Originally Posted by jrgme View Post
    I am interested in this as well. Is there updates to the code to work in VB10?
    Try this attachment!
    Attached Files Attached Files
    Last edited by Nightwalker83; Apr 8th, 2012 at 06:56 AM. Reason: Fixed attachment!
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    Please consider giving me some rep points if I help you a lot.
    Links to my code examples can now be found on my website: My websites
    Please rate my post if you find it helpful!
    Technology is a dangerous thing in the hands of an idiot! I am that idiot.

  35. #35
    New Member
    Join Date
    Apr 2012
    Posts
    2

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

    Thanks man! I am really new to this stuff (although like many some background in coding). I want to run two commands through the command line. I need to first set the directory to a folder such as c:\HTDP and then call a program and file in that directory so htdp < c:\ngs\htdp\sample.txt. The file will later be set as a variable but this process will remain the same so I would like to hard code it into the background. Any suggestions?

    I am later going to write code that manipulates the text file before to a specific format from variables and after to another specific format.

  36. #36
    New Member
    Join Date
    Apr 2012
    Posts
    13

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

    I tried this and I don't get any results in the textbox?

    Any Ideas why?

    I tried the original one and it quickly displays the dos screen and goes away.

    I'm more concern withe the version 10 not working.

    Thanks for the help.

    Quote Originally Posted by Nightwalker83 View Post
    Try this attachment!

  37. #37
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,191

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

    If it displays incorrectly on your computer not matter which version of the project you are using you are most likely doing something wrong.

    Which version of VS are you using? Have you modified any of the code from either of the above projects before you attempt to run them? If so which parts of the code do you modify?
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    Please consider giving me some rep points if I help you a lot.
    Links to my code examples can now be found on my website: My websites
    Please rate my post if you find it helpful!
    Technology is a dangerous thing in the hands of an idiot! I am that idiot.

  38. #38
    New Member
    Join Date
    Apr 2012
    Posts
    13

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

    That is the thing, I have not modified anything yet. I compiled it to see how it works and just test it out.

    All I did was extract the zip files and launch it in VS 2010. No errors but when I run it nothing happens.



    Quote Originally Posted by Nightwalker83 View Post
    If it displays incorrectly on your computer not matter which version of the project you are using you are most likely doing something wrong.

    Which version of VS are you using? Have you modified any of the code from either of the above projects before you attempt to run them? If so which parts of the code do you modify?

  39. #39
    PowerPoster Nightwalker83's Avatar
    Join Date
    Dec 2001
    Location
    Adelaide, Australia
    Posts
    13,191

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

    This is the output I get when upgrading uniquegodwin's code to VS2010:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation. All rights reserved.

    20/04/2012 08:16 PM <DIR> .
    20/04/2012 08:16 PM <DIR> ..
    20/04/2012 08:16 PM 23,552 2010CMDExample.exe
    20/04/2012 08:16 PM 46,592 2010CMDExample.pdb
    20/04/2012 08:17 PM 11,600 2010CMDExample.vshost.exe
    20/04/2012 08:16 PM 691 2010CMDExample.xml
    4 File(s) 82,435 bytes
    2 Dir(s) 426,662,567,936 bytes free
    Did you follow the example in post #1? That is, type "Dir" to the "txtCommand" textbox and click the "Send" button.
    when you quote a post could you please do it via the "Reply With Quote" button or if it multiple post click the "''+" button then "Reply With Quote" button.
    If this thread is finished with please mark it "Resolved" by selecting "Mark thread resolved" from the "Thread tools" drop-down menu.
    Please consider giving me some rep points if I help you a lot.
    Links to my code examples can now be found on my website: My websites
    Please rate my post if you find it helpful!
    Technology is a dangerous thing in the hands of an idiot! I am that idiot.

  40. #40
    New Member
    Join Date
    Apr 2012
    Posts
    13

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

    Working now. I didn't do anything different

    My mind was already in weekend mode. Thanks though

    Quote Originally Posted by Nightwalker83 View Post
    This is the output I get when upgrading uniquegodwin's code to VS2010:



    Did you follow the example in post #1? That is, type "Dir" to the "txtCommand" textbox and click the "Send" button.

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
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.