How to hide cmd window while running a batch file? - c#

How to hide cmd window while running a batch file?
I use the following code to run batch file
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();

If proc.StartInfo.UseShellExecute is false, then you are launching the process and can use:
proc.StartInfo.CreateNoWindow = true;
If proc.StartInfo.UseShellExecute is true, then the OS is launching the process and you have to provide a "hint" to the process via:
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
However the called application may ignore this latter request.
If using UseShellExecute = false, you might want to consider redirecting standard output/error, to capture any logging produced:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
And have a function like
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
There's a good page covering CreateNoWindow this on an MSDN blog.
There is also a bug in Windows which may throw a dialog and defeat CreateNoWindow if you are passing a username/password. For details
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476
http://support.microsoft.com/?kbid=818858

According to the Process properties, you do have a:
Property: CreateNoWindow
Notes: Allows you to run a command line program silently.
It does not flash a console window.
and:
Property: WindowStyle
Notes: Use this to set windows as hidden.
The author has used ProcessWindowStyle.Hidden often.
As an example!
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}

Use:
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

This is what worked for me,
When you redirect all of the input and output, and set the window hidden it should work
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;

try with this and this where the c# code is embedded into the batch files:
#echo off
echo self minimizing
call getCmdPid.bat
call windowMode.bat -pid %errorlevel% -mode minimized
echo --other commands--
pause
Though it might be not so easy to unhide the window.

Related

Run .exe from another app and enter values automatically

I want to run .exe file from another app, which is console app in .NET Core. When the app is open I want to write input to console from my code. Something like this:
var cmd = System.Diagnostics.Process.Start("myApp.exe");
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("MyName"); // this should be entered in console as username
So I specify username from my code, instead of writing it to console manually. Code above is not working for me. Is there a way to do this?
enter username
You're first starting the Process and then you're manipulating the startup arguments. You need to start the process afterwards.
use something like this instead:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false; //required to redirect standart input/output
// redirects on your choice
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.FileName = ...app path to execute...;
startInfo.Arguments = ...argumetns if required...;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(...write whatever you want...);
source
You need redirect standard input. Create ProcessStartInfo structure, then start a process and after process started write to the process standart input
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
FileName = pathToApplication,
RedirectStandardInput = true,
UseShellExecute = false
};
Process process = Process.Start(processStartInfo);
var writer = process.StandardInput;
writer.WriteLine("MyName");
Console.ReadLine();

How to auto fill cmd prompt

I Have a C# program; when I hit a button I want it to open a CMD window, then automatically type in the cmd window and run that said command. So far I have this from 4 hours of research. But nothing is working.
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
//p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ipconfig");
Any idea on how to fill in a certain text then automatically run it when the button is hit?
With StandardInput and StandardOutput redirected, you cannot see the new window opened. If you want to create a new cmd window and run ipconfig in it, you could do this:
var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c ipconfig & pause";
p.Start();
I agree that if all you want to do is execute "ipconfig" you could just invoke it instead of cmd.exe. Assuming you want to do other things with cmd.exe, here is an example of how to invoke it, have it execute a command, and then terminate (using the /K switch instead of /C will keep cmd.exe running):
using System;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C ipconfig";
p.Start();
var output = p.StandardOutput.ReadToEnd();
Console.Write(output);
Console.ReadKey();
}
}
}

how to start process with hidden window

I have this code:
string d = "-f image2 -framerate 9 -i E:\\REC\\Temp\\%06d.jpeg -r 30 E:\\REC\\Video\\" + label1.Text + ".avi";
//string d = "-f dshow -i video=\"screen-capture-recorder\" E:\\REC\\" + label1.Text + ".flv";
Process proc = new Process();
proc.StartInfo.FileName = "E:\\ffmpeg\\bin\\ffmpeg.exe";
proc.StartInfo.Arguments = d;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
if (!proc.Start())
{
Console.WriteLine("Error starting");
return;
}
proc.WaitForExit();
When it runs the ffmpeg.exe is there like this:
My question is how to hide this window?
You need the following combination of settings:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
And that's it.
The reason being that the key setting is CreateNoWindow which has to be true. But CreateNoWindow only has any effect when UseShellExecute is false. That's because CreateNoWindow maps to the CREATE_NO_WINDOW process creation flag passed to CreateProcess. And CreateProcess is only called when UseShellExecute is false.
More information can be found from the documentation:
Property Value
true if the process should be started without creating a new window to contain it; otherwise, false. The default is false.
Remarks
If the UseShellExecute property is true or the UserName and Password
properties are not null, the CreateNoWindow property value is ignored
and a new window is created.
This on keeps the all processes in same console window. no allow to open an new one`
Process process = new Process();
// Stop the process from opening a new window
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
// Setup executable and parameters
process.StartInfo.FileName = #"E:\\ffmpeg\\bin\\ffmpeg.exe"
//Optional
string d = "-f image2 -framerate 9 -i E:\\REC\\Temp\\%06d.jpeg -r 30 E:\\REC\\Video\\" + label1.Text + ".avi";
process.StartInfo.Arguments = d;
// Go
process.Start();

Hide console window from Process.Start C#

I am trying to create process on a remote machine using using System.Diagnostics.Process class.
I am able to create a process. But the problem is, creating a service is take a long time and console window is displayed.
Another annoying thing is the console window is displayed on top of my windows form and i cant do any other operations on that form.
I have set all properties like CreateNoWindow = true,
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
but still it shows the console window. even i have redirected output and errors to seperate stream but no luck.
Is there any other way to hide the Console window? Please help me out .
Here is the part of my code i used to execute sc command.
Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.FileName = "sc";
proc.StartInfo.Arguments = string.Format(#"\\SYS25 create MySvc binPath= C:\mysvc.exe");
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();
I had a similar issue when attempting to start a process without showing the console window. I tested with several different combinations of property values until I found one that exhibited the behavior I wanted.
Here is a page detailing why the UseShellExecute property must be set to false.
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.createnowindow.aspx
Under Remarks section on page:
If the UseShellExecute property is true or the UserName and
Password properties are not null, the CreateNoWindow property
value is ignored and a new window is created.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fullPath;
startInfo.Arguments = args;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
}
catch (Exception e)
{
throw;
}
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
This should work, try;
Add a System Reference.
using System.Diagnostics;
Then use this code to run your command in a hiden CMD Window.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();
This doesn't show the window:
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;
...
cmd.Start();

Running an exe in C# with commandline parameters, suppressing the dos window

I am using lame for transcoding for one of my project. The issue is that when I call lame from C#, a DOS window pops out. Is there any way I can suppress this?
Here is my code so far:
Process converter =
Process.Start(lameExePath, "-V2 \"" + waveFile + "\" \"" + mp3File + "\"");
converter.WaitForExit();
Did you try something like:
using( var process = new Process() )
{
process.StartInfo.FileName = "...";
process.StartInfo.WorkingDirectory = "...";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.Start();
}
Assuming you are calling it via Process.Start, you can use the overload that takes ProcessStartInfo that has its CreateNoWindow property set to true and its UseShellExecute set to false.
The ProcessStartInfo object can also be accessed via the Process.StartInfo property and can be set there directly before starting the process (easier if you have a small number of properties to setup).
Process bhd = new Process();
bhd.StartInfo.FileName = "NSOMod.exe";
bhd.StartInfo.Arguments = "/mod NSOmod /d";
bhd.StartInfo.CreateNoWindow = true;
bhd.StartInfo.UseShellExecute = false;
Is another way.
This is my code that does a similar thing, (and also reads the output and return code)
process.StartInfo.FileName = toolFilePath;
process.StartInfo.Arguments = parameters;
process.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none
process.StartInfo.WorkingDirectory = Path.GetDirectoryName(toolFilePath);
process.StartInfo.Domain = domain;
process.StartInfo.UserName = userName;
process.StartInfo.Password = decryptedPassword;
process.Start();
output = process.StandardOutput.ReadToEnd(); // read the output here...
process.WaitForExit(); // ...then wait for exit, as after exit, it can't read the output
returnCode = process.ExitCode;
process.Close(); // once we have read the exit code, can close the process

Categories