Hide process window - c#

I have a process that I need hidden, I have tried the following lines of code to make it hidden:
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
The first line just simply does not make it non-visible and the second throws the following error:
"{"StandardOut has not been redirected or the process hasn't started yet."}
Also I need to have the output redirected to a richtextbox and the clipboard, so I cannot set redirectstandardoutput to false.
Here is my function for creating the process.
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = pingData;
p.Start();
p.WaitForExit();
string result = p.StandardOutput.ReadToEnd();
System.Windows.Forms.Clipboard.SetText(result);
if(p.HasExited)
{
richTextBox1.Text = result;
outPut = result;
MessageBox.Show( "Ping request has completed. \n Results have been copied to the clipboard.");
}
Thanks

Remove the following line:
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Keep these two lines:
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
WindowStyle only applies to native Windows GUI applications.

Related

Run a C# exe with parameters that is to start another application and get output from console

I have an exe which has some parameters- path of another application and some files to be opened from that application. There would be an output as part of that application which would be displayed in the console of my exe.
But i am unable to get the output from the console.
I have the code:
ProcessStartInfo psi = new ProcessStartInfo("\"" + dllpath + "\\newapplication.exe" + "\"");
Process p = new Process();
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
p.Start();
The process starts successfully, and then i have to open a file in the process which happens through another class. So after the file opened, some extraction happens and the result is displayed on the console.
When i give p.WaitForExit(); nothing happens other than starting the application! How do i acheive to retreive the output on StandardOutput as per my code? Need Help!
This is the correct way to do it:
string outputProcess = "";
string errorProcess = "";
using (Process process = new Process())
{
process.StartInfo.FileName = path;
process.StartInfo.Arguments = arguments;
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
outputProcess = process.StandardOutput.ReadToEnd();
errorProcess = process.StandardError.ReadToEnd();
process.WaitForExit();
}
Remember to use the using statement when you have an IDisposable object

Reading cmd output real time

I'm writing a program that reads python script output and shows the results in textbox.
Since the script runnning for a long time, I want to be able to see the output every 1 second (or after each line is writen).
Now i can see the output only when the process ends.
Does someone know what is the problem?
snippet of my code:
Process p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.OutputDataReceived += new DataReceivedEventHandler (p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler (p_ErrorDataReceived);
p.Exited += new EventHandler (p_Exited);
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "python.exe";
p.StartInfo.Arguments = "path " + commandline;
p.Start();
StreamReader s = p.StandardOutput;
String output = s.ReadToEnd();
textBox3.Text = output;
p.WaitForExit();
I'm doing it the following way in my own programs:
private static void startProgram(
string commandLine )
{
var fileName = commandLine;
var arguments = string.Empty;
checkSplitFileName( ref fileName, ref arguments );
var info = new ProcessStartInfo();
info.FileName = fileName;
info.Arguments = arguments;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
using ( var p = new Process() )
{
p.StartInfo = info;
p.EnableRaisingEvents = true;
p.OutputDataReceived += (s,o) => {
Console.WriteLine(o.Data);
};
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
}
}
I.e. I'm subscribing to the OutputDataReceived event and calling BeginOutputReadLine method. See also this similar Stack Overflow question.
(The method checkSplitFileName in my above source code can be found here)
I had this same problem running my Python script from C#. The problem is that Python buffers the output from stdout (print()).
You could do one of two things here.
1.
Add the following to your Python script, after every print() line to flush the output.
import sys
print('Hello World!')
sys.stdout.flush()
2.
Run the Python compiler with the -u command line parameter. This way you don't need to add the above flush line after every print.
...
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "python.exe -u path " + commandline;
...
Python, by default, buffers its output.
The way to go is to pass a "-u" command line argument to python.
so if you want to execute say hello.py, you would do :
python.exe -u hello.py
Heres the C# code that works for me.
Process p = new Process();
string op = "";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "c:\\python27\\python.exe";
StreamReader outputStream = p.StandardOutput;
StreamReader errorStream = p.StandardError;
p.StartInfo.Arguments = #"-u hello.py";
p.Start();
string output = "";
int offset = 0, readBytes = 0;
char[] buffer = new char[512];
do
{
output = outputStream.ReadLine();
if (!string.IsNullOrEmpty(output))
{
txtOutput.AppendText(output);
txtOutput.AppendText(Environment.NewLine);
offset += readBytes;
Application.DoEvents();
}
Thread.Sleep(3);
} while (!p.HasExited);

Set waiting time for process to exit

I am using the following command to run the bat file:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.FileName = "d:/my.bat";
p.Start();
p.WaitForExit(2000000);
p.Close();
p.Dispose();
My problem is that I need to wait until the above process get completed and close it as soon as it is possible.
Any suggestions?
You can replace p.WaitForExit(2000000) with p.WaitForExit(); in order to manage the case where the process takes longer than 2000000 milliseconds to run.
Link
Just use WaitForExit without any parameter like:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.FileName = "d:/my.bat";
p.Start();
p.WaitForExit();
p.Close();
p.Dispose();
It will wait until your process is done. See the documentation on MSDN for more info.
Alternatively, and especially if you want to give feedback to the user, you can do something like this:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.FileName = "d:/my.bat";
Console.Write("Running {0} ", p.StartInfo.FileName)
p.Start();
while (!p.HasExited)
{
Console.Write(".");
// wait one second
Thread.Sleep(1000);
}
Console.WriteLine(" done.");
p.Close();
p.Dispose();

how to change the directory location in command prompt using C#?

I have successfully opened command prompt window using C# through the following code.
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = #"d:\pdf2xml";
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.WriteLine(#"pdftoxml.win32.1.2.7 -annotation "+filename);
p.StandardInput.WriteLine(#"cd D:\python-source\ds-xmlStudio-1.0-py27");
p.StandardInput.WriteLine(#"main.py -i example-8.xml -o outp.xml");
p.WaitForExit();
But, i have also passed command to change the directory.
problems:
how to change the directory location?
Cmd prompt will be shown always after opened...
Please guide me to get out of those issue...
To change the startup directory, you can change it by setting p.StartInfo.WorkingDirectory to the directory that you are interested in. The reason that your directory is not changing is because the argument /c d:\test. Instead try /c cd d:\test
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = #"C:\";
p.StartInfo.UseShellExecute = false;
...
p.Start();
You can hide the command prompt by setting p.StartInfo.WindowStyle to Hidden to avoid showing that window.
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.windowstyle.aspx
You can use p.StandardInput.WriteLine to send commands to cmd window. For this just set the p.StartInfo.RedirectStandardOutput to ture. like below
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
//p.StartInfo.Arguments = #"/c D:\\pdf2xml";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.WriteLine(#"cd D:\pdf2xml");
p.StandardInput.WriteLine("d:");
use System.IO.Directory.SetCurrentDirectory instead
You may also Check this
and this post
processStartInfo .WorkingDirectory = #"c:\";

Why does Shellexecute=false break this?

I'm learning C# at the moment for a bit of fun and am trying to make a windows application that has a bit of a gui for running some python commands. Basically, I'm trying to teach myself the guts of running a process and sending commands to it, as well as receiving commands from it.
I have the following code at the moment:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "C:/Python31/python.exe";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
textBox1.Text = output;
Running python.exe from a command prompt gives some introductory text that I'd like to capture and send to a textbox in the windows form (textBox1). Basically, the goal is to have something that looks like the python console running from the windows app. When I don't set UseShellExecute to false, a console pops up and everything runs fine; however, when I set UseShellExecute to false in order to re-direct the input, all I get is that a console pops up very quickly and closes again.
What am I doing wrong here?
For some reason, you shouldn't use forward slashes when you start the process.
Compare (does not work):
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "C:/windows/system32/cmd.exe";
p.StartInfo.Arguments = "/c dir" ;
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
bool f = p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
[...]
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
to (works as expected):
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = #"C:\windows\system32\cmd.exe";
p.StartInfo.Arguments = "/c dir" ;
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
bool f = p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
[...]
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
Python seems to be doing something weird. I wouldn't believe it until I tested it and then did some research. But all of these posts basically seem to have the same exact problem:
https://stackoverflow.com/questions/4106095/capturing-standard-output-from-django-using-c
Python & C#: Is IronPython absolutely necessary?
C# capturing python.exe output and displaying it in textbox
Certain Python commands aren't caught in Stdout

Categories

Resources