|
|||||||
|
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
"The" RedHeadedLefty
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
![]() ![]() ![]() ![]() ![]() |
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:
Last edited by gigemboy; Sep 12th, 2006 at 12:51 PM. |
|
|
|
|
|
#2 |
|
Super Moderator
Join Date: Apr 01
Location: LA, Calif. Raiders #1 AKA:Gangsta Yoda™
Posts: 58,848
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
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 Posts • VS.NET on Vista (New) • Multiple .NET Framework Versions (New) • Office Primary Interop Assemblies • VB/Office Guru™ Word SpellChecker™.NET • VB/Office Guru™ Word SpellChecker™ VB6 • VB.NET Attributes Ex. • Outlook Global Address List • API 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 |
|
|
|
|
|
#3 |
|
Member
Join Date: Feb 06
Posts: 35
![]() |
Re: Automate Command Prompt Window (CMD), Redirect Output to Application
I get an "InvalidOperationException"...
|
|
|
|
|
|
#4 |
|
"The" RedHeadedLefty
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
![]() ![]() ![]() ![]() ![]() |
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:
|
|
|
|
|
|
#5 |
|
New Member
Join Date: Mar 06
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 |
|
"The" RedHeadedLefty
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
![]() ![]() ![]() ![]() ![]() |
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 |
|
New Member
Join Date: Jul 06
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 |
|
Fanatic Member
Join Date: Jul 06
Location: MI
Posts: 1,007
![]() |
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 |
|
"The" RedHeadedLefty
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
![]() ![]() ![]() ![]() ![]() |
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. |
|
|
|
|
|
#10 |
|
"The" RedHeadedLefty
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
![]() ![]() ![]() ![]() ![]() |
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:
Last edited by gigemboy; Sep 12th, 2006 at 12:46 PM. |
|
|
|
|
|
#11 |
|
Fanatic Member
Join Date: Jul 05
Location: Chennai,India
Posts: 693
![]() |
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
__________________
Godwin Help someone else with what someone helped you! |
|
|
|
|
|
#12 |
|
"The" RedHeadedLefty
Join Date: Aug 05
Location: College Station, TX Preferred Nickname: Gig Current Mood: Just Peachy Turnons: String Manipulation
Posts: 4,484
![]() ![]() ![]() ![]() ![]() |
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 |
|
Junior Member
Join Date: Aug 06
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 |
|
Hyperactive Member
Join Date: Jul 04
Posts: 444
![]() |
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
__________________
[2003] [2005] Be sure to run the following examples with the "Start without debugging" button, since the debugger causes the code to behave differently. UAC(User Account Control) | On Screen Keyboard | Shutdown Manager| SendKeys(With directive focus) | WaitToComplete(.wav) | Hide from Task Manager | Control Ctrl+Alt+Delete, Win+Keys, and Alt+F4 | AlwaysOnTop | Hide Taskbar | Simple "On screen keyboard" | Pin to start menu(VB6) | Pin to start menu(NET) | VB2005 without SP2 | Remove TitleBar menu items | SwapKeyboardKeys | Disabled MenuStrip bug fix | Aero Vista/7 | Flip3D TopMost Vista/7 | Dim desktop TrackBar | Accessibility API |
|
|
|
|
|
#15 | |
|
Member
Join Date: Jul 07
Location: Silly Clone Valley CA
Posts: 47
![]() |
Re: Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]
Quote:
|
|
|
|
|
|
|
#16 |
|
Hyperactive Member
Join Date: Jul 04
Posts: 444
![]() |
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.
__________________
[2003] [2005] Be sure to run the following examples with the "Start without debugging" button, since the debugger causes the code to behave differently. UAC(User Account Control) | On Screen Keyboard | Shutdown Manager| SendKeys(With directive focus) | WaitToComplete(.wav) | Hide from Task Manager | Control Ctrl+Alt+Delete, Win+Keys, and Alt+F4 | AlwaysOnTop | Hide Taskbar | Simple "On screen keyboard" | Pin to start menu(VB6) | Pin to start menu(NET) | VB2005 without SP2 | Remove TitleBar menu items | SwapKeyboardKeys | Disabled MenuStrip bug fix | Aero Vista/7 | Flip3D TopMost Vista/7 | Dim desktop TrackBar | Accessibility API |
|
|
|
|
|
#17 | |
|
Member
Join Date: Jul 07
Location: Silly Clone Valley CA
Posts: 47
![]() |
Re: Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]
Quote:
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 |
|
Hyperactive Member
Join Date: Jul 04
Posts: 444
![]() |
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.
__________________
[2003] [2005] Be sure to run the following examples with the "Start without debugging" button, since the debugger causes the code to behave differently. UAC(User Account Control) | On Screen Keyboard | Shutdown Manager| SendKeys(With directive focus) | WaitToComplete(.wav) | Hide from Task Manager | Control Ctrl+Alt+Delete, Win+Keys, and Alt+F4 | AlwaysOnTop | Hide Taskbar | Simple "On screen keyboard" | Pin to start menu(VB6) | Pin to start menu(NET) | VB2005 without SP2 | Remove TitleBar menu items | SwapKeyboardKeys | Disabled MenuStrip bug fix | Aero Vista/7 | Flip3D TopMost Vista/7 | Dim desktop TrackBar | Accessibility API |
|
|
|
|
|
#19 |
|
Member
Join Date: Jul 07
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
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 | |
|
Hyperactive Member
Join Date: Jul 04
Posts: 444
![]() |
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:
__________________
[2003] [2005] Be sure to run the following examples with the "Start without debugging" button, since the debugger causes the code to behave differently. UAC(User Account Control) | On Screen Keyboard | Shutdown Manager| SendKeys(With directive focus) | WaitToComplete(.wav) | Hide from Task Manager | Control Ctrl+Alt+Delete, Win+Keys, and Alt+F4 | AlwaysOnTop | Hide Taskbar | Simple "On screen keyboard" | Pin to start menu(VB6) | Pin to start menu(NET) | VB2005 without SP2 | Remove TitleBar menu items | SwapKeyboardKeys | Disabled MenuStrip bug fix | Aero Vista/7 | Flip3D TopMost Vista/7 | Dim desktop TrackBar | Accessibility API |
|
|
|
|
|
|
#21 | |||
|
New Member
Join Date: Jul 08
Posts: 1
![]() |
Re: Automate Command Prompt Window (CMD), Redirect Output to Application
Quote:
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:
Quote:
I need to make this work... and I am running out of time...
|
|||
|
|
|
|
|
#22 |
|
Junior Member
Join Date: Jan 09
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 | |
|
Hyperactive Member
Join Date: Jul 04
Posts: 444
![]() |
Re: Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]
Quote:
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
__________________
[2003] [2005] Be sure to run the following examples with the "Start without debugging" button, since the debugger causes the code to behave differently. UAC(User Account Control) | On Screen Keyboard | Shutdown Manager| SendKeys(With directive focus) | WaitToComplete(.wav) | Hide from Task Manager | Control Ctrl+Alt+Delete, Win+Keys, and Alt+F4 | AlwaysOnTop | Hide Taskbar | Simple "On screen keyboard" | Pin to start menu(VB6) | Pin to start menu(NET) | VB2005 without SP2 | Remove TitleBar menu items | SwapKeyboardKeys | Disabled MenuStrip bug fix | Aero Vista/7 | Flip3D TopMost Vista/7 | Dim desktop TrackBar | Accessibility API |
|
|
|
|
|
|
#24 |
|
Junior Member
Join Date: Jan 09
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
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 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 |
|
Junior Member
Join Date: Jan 09
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 |
|
Addicted Member
Join Date: May 09
Posts: 229
![]() |
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 |
|
Banned
Join Date: Jun 09
Posts: 12
![]() |
Re: Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]
is this to control cmd ??
|
|
|
|
![]() |
|
||||||
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|