To register for an Internet.com membership to receive newsletters and white papers, use the Register button ABOVE.
To participate in the message forums BELOW, click here
VBForums  

VB Wire News
Article :: Building Dynamic Systems with Expressions in .NET
How Is XML Like An Interface?
Understanding Covariance and Contravariance
Print VS 2010 Keyboard Shortcut References in Letter (8.5x11in) and A4 (210×297mm) Sizes
Updated Productivity Power Tools



Go Back   VBForums > VBForums CodeBank > CodeBank - Visual Basic .NET

Reply Post New Thread
 
Thread Tools Display Modes
Old Jan 14th, 2006, 01:33 AM   #1
gigemboy
"The" RedHeadedLefty
 
gigemboy's Avatar
 
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)
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 Files
File Type: zip CmdRedirect.zip (23.2 KB, 2162 views)

Last edited by gigemboy; Sep 12th, 2006 at 12:51 PM.
gigemboy is offline   Reply With Quote
Old Jan 14th, 2006, 09:05 AM   #2
RobDog888
Super Moderator
 
RobDog888's Avatar
 
Join Date: Apr 01
Location: LA, Calif. Raiders #1 AKA:Gangsta Yoda™
Posts: 58,848
RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)RobDog888 has a brilliant future (2000+)
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, 2007, 2008, 2009, 2010
Office Development FAQ (VBA, VB 6, VB.NET, C#)
Software Engineer MCP (VB 6 & .NET), BSEE, CET (Internet.com's #1 Poster)
If a post has helped you then Please Rate it!
Star Wars Gangsta Rap Reps & Rating PostsVS.NET on Vista (New)Multiple .NET Framework Versions (New)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 150 GB HDs RAID 1, 2 GBs DDR2 667 MHz RAM, 3 Viewsonic 17" LCDs, Windows Vista RTM, IE 7, Office 2007
RobDog888 is offline   Reply With Quote
Old Feb 27th, 2006, 05:47 AM   #3
nbmprivat
Member
 
Join Date: Feb 06
Posts: 35
nbmprivat is an unknown quantity at this point (<10)
Re: Automate Command Prompt Window (CMD), Redirect Output to Application

I get an "InvalidOperationException"...
nbmprivat is offline   Reply With Quote
Old Mar 15th, 2006, 07:38 PM   #4
gigemboy
"The" RedHeadedLefty
 
gigemboy's Avatar
 
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)
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()
gigemboy is offline   Reply With Quote
Old Mar 28th, 2006, 02:22 AM   #5
Jan1503
New Member
 
Join Date: Mar 06
Posts: 1
Jan1503 is an unknown quantity at this point (<10)
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.
Jan1503 is offline   Reply With Quote
Old May 18th, 2006, 04:03 PM   #6
gigemboy
"The" RedHeadedLefty
 
gigemboy's Avatar
 
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)
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.
gigemboy is offline   Reply With Quote
Old Jul 20th, 2006, 01:37 PM   #7
sonitin
New Member
 
Join Date: Jul 06
Posts: 2
sonitin is an unknown quantity at this point (<10)
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,
sonitin is offline   Reply With Quote
Old Sep 12th, 2006, 10:04 AM   #8
nbrege
Fanatic Member
 
Join Date: Jul 06
Location: MI
Posts: 1,007
nbrege will become famous soon enough (65+)
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...
nbrege is offline   Reply With Quote
Old Sep 12th, 2006, 12:09 PM   #9
gigemboy
"The" RedHeadedLefty
 
gigemboy's Avatar
 
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)
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 12:16 PM.
gigemboy is offline   Reply With Quote
Old Sep 12th, 2006, 12:38 PM   #10
gigemboy
"The" RedHeadedLefty
 
gigemboy's Avatar
 
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)
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.     Private Results As String
  3.     Private Delegate Sub delUpdate()
  4.     Private Finished As New delUpdate(AddressOf UpdateText)
  5.     Private Sub UpdateText()
  6.         txtResults.Text = Results
  7.     End Sub
  8.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  9.         Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
  10.         CMDThread.Start()
  11.     End Sub
  12.     Private Sub CMDAutomate()
  13.         Dim myprocess As New Process
  14.         Dim StartInfo As New System.Diagnostics.ProcessStartInfo
  15.         StartInfo.FileName = "cmd" 'starts cmd window
  16.         StartInfo.RedirectStandardInput = True
  17.         StartInfo.RedirectStandardOutput = True
  18.         StartInfo.UseShellExecute = False 'required to redirect
  19.         StartInfo.CreateNoWindow = True 'creates no cmd window
  20.         myprocess.StartInfo = StartInfo
  21.         myprocess.Start()
  22.         Dim SR As System.IO.StreamReader = myprocess.StandardOutput
  23.         Dim SW As System.IO.StreamWriter = myprocess.StandardInput
  24.         SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
  25.         SW.WriteLine("exit") 'exits command prompt window
  26.         Results = SR.ReadToEnd 'returns results of the command window
  27.         SW.Close()
  28.         SR.Close()
  29.         'invokes Finished delegate, which updates textbox with the results text
  30.         Invoke(Finished)
  31.     End Sub
Attached Files
File Type: zip 2005CMDExample.zip (15.5 KB, 1063 views)

Last edited by gigemboy; Sep 12th, 2006 at 12:46 PM.
gigemboy is offline   Reply With Quote
Old Sep 25th, 2006, 01:44 AM   #11
uniquegodwin
Fanatic Member
 
uniquegodwin's Avatar
 
Join Date: Jul 05
Location: Chennai,India
Posts: 693
uniquegodwin will become famous soon enough (50+)
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
File Type: zip 2005CMDExample.zip (54.4 KB, 887 views)
__________________
Godwin

Help someone else with what someone helped you!
uniquegodwin is offline   Reply With Quote
Old Sep 26th, 2006, 04:24 PM   #12
gigemboy
"The" RedHeadedLefty
 
gigemboy's Avatar
 
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)gigemboy is a glorious beacon of light (400+)
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...
gigemboy is offline   Reply With Quote
Old Feb 15th, 2007, 01:38 PM   #13
w8taminute
Junior Member
 
w8taminute's Avatar
 
Join Date: Aug 06
Posts: 24
w8taminute is an unknown quantity at this point (<10)
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?
w8taminute is offline   Reply With Quote
Old Jun 7th, 2007, 08:36 PM   #14
TTn
Hyperactive Member
 
TTn's Avatar
 
Join Date: Jul 04
Posts: 444
TTn  is on a distinguished road (30+)
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!
TTn is offline   Reply With Quote
Old Jul 13th, 2007, 02:44 PM   #15
SlumberMachine
Member
 
Join Date: Jul 07
Location: Silly Clone Valley CA
Posts: 47
SlumberMachine is an unknown quantity at this point (<10)
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.
SlumberMachine is offline   Reply With Quote
Old Jul 14th, 2007, 03:44 AM   #16
TTn
Hyperactive Member
 
TTn's Avatar
 
Join Date: Jul 04
Posts: 444
TTn  is on a distinguished road (30+)
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.
TTn is offline   Reply With Quote
Old Jul 16th, 2007, 01:52 AM   #17
SlumberMachine
Member
 
Join Date: Jul 07
Location: Silly Clone Valley CA
Posts: 47
SlumberMachine is an unknown quantity at this point (<10)
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.
SlumberMachine is offline   Reply With Quote
Old Jul 16th, 2007, 10:30 AM   #18
TTn
Hyperactive Member
 
TTn's Avatar
 
Join Date: Jul 04
Posts: 444
TTn  is on a distinguished road (30+)
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.
TTn is offline   Reply With Quote
Old Jul 16th, 2007, 12:02 PM   #19
SlumberMachine
Member
 
Join Date: Jul 07
Location: Silly Clone Valley CA
Posts: 47
SlumberMachine is an unknown quantity at this point (<10)
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.
SlumberMachine is offline   Reply With Quote
Old Jul 16th, 2007, 12:54 PM   #20
TTn
Hyperactive Member
 
TTn's Avatar
 
Join Date: Jul 04
Posts: 444
TTn  is on a distinguished road (30+)
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:

Quote:
"'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.
TTn is offline   Reply With Quote
Old Jul 8th, 2008, 09:34 PM   #21
Galdhrim
New Member
 
Join Date: Jul 08
Posts: 1
Galdhrim is an unknown quantity at this point (<10)
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.     Private Results As String
  3.     Private Delegate Sub delUpdate()
  4.     Private Finished As New delUpdate(AddressOf UpdateText)
  5.     Private Sub UpdateText()
  6.         txtResults.Text = Results
  7.     End Sub
  8.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  9.         Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
  10.         CMDThread.Start()
  11.     End Sub
  12.     Private Sub CMDAutomate()
  13.         Dim myprocess As New Process
  14.         Dim StartInfo As New System.Diagnostics.ProcessStartInfo
  15.         StartInfo.FileName = "cmd" 'starts cmd window
  16.         StartInfo.RedirectStandardInput = True
  17.         StartInfo.RedirectStandardOutput = True
  18.         StartInfo.UseShellExecute = False 'required to redirect
  19.         StartInfo.CreateNoWindow = True 'creates no cmd window
  20.         myprocess.StartInfo = StartInfo
  21.         myprocess.Start()
  22.         Dim SR As System.IO.StreamReader = myprocess.StandardOutput
  23.         Dim SW As System.IO.StreamWriter = myprocess.StandardInput
  24.         SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
  25.         SW.WriteLine("exit") 'exits command prompt window
  26.         Results = SR.ReadToEnd 'returns results of the command window
  27.         SW.Close()
  28.         SR.Close()
  29.         'invokes Finished delegate, which updates textbox with the results text
  30.         Invoke(Finished)
  31.     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:
Quote:
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:

Quote:
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...
Galdhrim is offline   Reply With Quote
Old Jan 20th, 2009, 01:06 PM   #22
Rock_Vacirca
Junior Member
 
Join Date: Jan 09
Posts: 31
Rock_Vacirca is an unknown quantity at this point (<10)
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?
Rock_Vacirca is offline   Reply With Quote
Old Jan 20th, 2009, 03:38 PM   #23
TTn
Hyperactive Member
 
TTn's Avatar
 
Join Date: Jul 04
Posts: 444
TTn  is on a distinguished road (30+)
Re: Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]

Quote:
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
TTn is offline   Reply With Quote
Old Jan 20th, 2009, 04:46 PM   #24
Rock_Vacirca
Junior Member
 
Join Date: Jan 09
Posts: 31
Rock_Vacirca is an unknown quantity at this point (<10)
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
Rock_Vacirca is offline   Reply With Quote
Old Jan 24th, 2009, 07:41 AM   #25
Rock_Vacirca
Junior Member
 
Join Date: Jan 09
Posts: 31
Rock_Vacirca is an unknown quantity at this point (<10)
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
Rock_Vacirca is offline   Reply With Quote
Old Jun 29th, 2009, 08:02 AM   #26
Cyb3rH4Xter
Addicted Member
 
Cyb3rH4Xter's Avatar
 
Join Date: May 09
Posts: 229
Cyb3rH4Xter is an unknown quantity at this point (<10)
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)
Cyb3rH4Xter is offline   Reply With Quote
Old Jun 29th, 2009, 07:07 PM   #27
SoulCollector
Banned
 
Join Date: Jun 09
Posts: 12
SoulCollector is an unknown quantity at this point (<10)
Re: Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]

is this to control cmd ??
SoulCollector is offline   Reply With Quote
Reply

Go Back   VBForums > VBForums CodeBank > CodeBank - Visual Basic .NET


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -5. The time now is 08:05 PM.





Acceptable Use Policy

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.