How to hide the Command Window using c# - c#

Building a console app that will execute an exe file(pagesnap.exe). I would like to hide its window(pagesnap.exe) during execution. How is it done.
ProcessStartInfo Psi = new ProcessStartInfo("D:\\PsTools\\");
Psi.FileName = "D:\\PsTools\\psexec.exe";
Psi.Arguments = #"/C \\DESK123 D:\files\pagesnap.exe";
Psi.UseShellExecute = false;
Psi.RedirectStandardOutput = true;
Psi.RedirectStandardInput = true;
Psi.WindowStyle = ProcessWindowStyle.Hidden;
Psi.CreateNoWindow = true;
Process.Start(Psi).WaitForExit();
DESK123 is the local PC. Would later try this with remote PCs.
Things I have tried
Psi.Arguments = #"/C start /b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 /b D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 D:\files\pagesnap.exe 2>&1 output.log";
Update: I have built pagesnap with Output type as a windows application instead of console. The cmd window doesn't come up, now. Seems this is the only way for me

Simply call the following function. Pass the argument as your command and your working directory
private string BatchCommand(string cmd, string mapD)
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd);
procStartInfo.WorkingDirectory = mapD;
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process cmdProcess = new System.Diagnostics.Process();
cmdProcess.StartInfo = procStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping www.google.com"); //Execute ping
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
// Get the output into a string
return Batchresults;
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
Batchresults += Environment.NewLine + e.Data.ToString();
}
void cmd_Error(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Batchresults += Environment.NewLine + e.Data.ToString();
}
}

Related

running cmd in c# answer yes to prompt

I'm running the below command from c#. There is a prompt that will be shown that I want to answer "yes" to how can I do this with the current code
If I run this as a batch script I can just do
echo y | pscp.exe -batch -pw password E:\\Certs\\client.conf me#<ip>:/home/user
which works - but unsure how I can replicate this using the below
string pscpPath="-batch -pw password E:\\Certs\\client.conf me#<ip>:/home/user";
ExecuteCopyCerts("pscp.exe", pscpPath);
Function:
public Boolean ExecuteCopyCerts(string fileName, string arguments)
{
txtLiveHubStatus.Text = "";
try
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
return proc.ExitCode == 0;
}
}
Set RedirectStandardInput to true
procStartInfo.RedirectStandardInput = true
and then write to StandardInput
proc.StandardInput.WriteLine("yes");
To reiterate what Hesam said though the prompt is Y, not yes. This is the prompt for the cert, which only occurs on the first call to each new linux machine. I use this code today in one of our applications.
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "pscp";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = $"-r -p -pw {passWord} \"{localFileNamePath}\" {userName}#{hostName}:{remotePath}";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
using (Process process = new Process())
{
process.StartInfo = psi;
process.Start();
process.StandardInput.WriteLine("Y");
process.WaitForExit();
}

Unable to open Visual Studio Command Prompt pragmatically using VS 2015

I want to run visual studios command programmatically.I have tried the above code but no help.All I am getting is a command prompt with my project`s directory open.
I have used Execute("VS140COMNTOOLS") as input.
private void Execute(string vsEnvVar) {
var vsInstallPath = Environment.GetEnvironmentVariable(vsEnvVar);
if (Directory.Exists(vsInstallPath)) {
var filePath = vsInstallPath + "vsvars32.bat";
if (File.Exists(filePath)) {
//start vs command process
Process proc = new Process();
var command = Environment.GetEnvironmentVariable("ComSpec");
command = #"" + command + #"";
//var batfile = #"E:\Test\vstest.bat";
var args = string.Format("/S/K \" \"{0}\" \"", filePath);
proc.StartInfo.FileName = command;
proc.StartInfo.Arguments = args;
//proc.StartInfo.RedirectStandardInput = true;
//proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.UseShellExecute = false;
proc.Start();
} else {
Console.WriteLine("File Does not exists " + filePath);
}
}
}
Try this:
private Process Execute(string vsEnvVar)
{
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");//assume location is in path. Otherwise use ComSpec env variable
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo = psi;
// attach output events
process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.StartInfo = psi;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.StandardInput.WriteLine(string.Format("call \"%{0}%vsvars32.bat\""), vsEnvVar);
process.StandardInput.Flush();
return process;
}
Now you can execute any commands by writing to process.StandardInput
process.StandardInput.WriteLine(#"msbuild c:\MySolution.sln /t:Clean");

Start command line with parameters and collection output

ProcessStartInfo startInfo = new ProcessStartInfo();
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "tsvc -a -st rifs -h "+textBox1+" -sn "+textBox2+" -status";
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
richTextBox1.Text = process.StandardOutput.ReadToEnd();
I need to run a command in cmd that will take 2 parameters that will be inserted to textBox1 and textBox2 and then sending the output to the richTextBox1.
When running it this way I get :
first chance exception of type 'System.InvalidOperationException' occurred in System.dll
Additional information: StandardOut has not been redirected or the process hasn't started yet
I tried to exclude the Output line , and when i do it does run CMD but does not type in any command (It just opens a CMD window and does nothing ) .
Process.Start() asynchronously starts a new process. When you get to the process.StandardOutput.ReadToEnd() the process is not finished yet, thus the exception. You should use eventing to hook into the OutputDataRecieved event. You want to do something like this:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c tsvc -a -st rifs -h " + textBox1 + " -sn " + textBox2 + " -status";
process.StartInfo = startInfo;
process.OutputDataReceived += ProcessOnOutputDataReceived;
process.ErrorDataReceived += ProcessOnOutputDataReceived;
process.Start();
and then add an event handler to the Output data recieved like so:
private void ProcessOnOutputDataReceived(object sender, DataReceivedEventArgs dataReceivedEventArgs)
{
richTextBox1.Text += dataReceivedEventArgs.Data;
}
Also, I am not certain but i think you need to call text on your textboxes:
startInfo.Arguments = "/c tsvc -a -st rifs -h " + textBox1.Text + " -sn " + textBox2.Text + " -status";
Managed to do it in the End with .
richTextBox1.Text = "";
int counter = 0 ,totalMemory=0;
string line;
string command = " /c ro -a -h " + textBox1.Text + " -sn HC* $$info Server Total = $servermemory Service Memory = $servicememory > c:\\noc\\ntb\\logs\\output.txt";
ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD", command);
Process proc = new Process();
procStartInfo.CreateNoWindow = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();

Hide Console Window while using Process.StartInfo with diffent Username

I'm starting a Process using a special User, Domain and Password. Although I told C# to hide the console window it is shown.
Here my code:
Process process = new Process();
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UserName = strUsername;
process.StartInfo.Domain = strDomain;
process.StartInfo.Password = secPassword;
process.StartInfo.FileName = "PsExec.exe";
process.StartInfo.Arguments = #"/accepteula -s \\" + strServername + #"program.exe";
process.Start();
process.WaitForExit();
I could find some hints in another forum:
If you call the Start(ProcessStartInfo) method with the
ProcessStartInfo..::.UserName and ProcessStartInfo..::.Password
properties set, the unmanaged CreateProcessWithLogonW function is
called, which starts the process in a new window even if the
CreateNoWindow property value is true or the WindowStyle property
value is Hidden.
Actually, I'm not really satisfied with this statement...
Thanks in advance.
Cheers
Alex
As i know there are workaround on this issue. You can launch hidden cmd with your params. Something like this:
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", String.Format("/accepteula -s \\{0}program.exe", strServername));
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process.Start(psi);
using (Process LMUTIL = new Process())
{
string arg1 ="argument"
LMUTIL.StartInfo.FileName = "program.exe";
LMUTIL.StartInfo.Arguments = arg1
LMUTIL.StartInfo.UseShellExecute = false;
LMUTIL.StartInfo.RedirectStandardOutput = true;
LMUTIL.StartInfo.CreateNoWindow = true;
LMUTIL.EnableRaisingEvents = true;
LMUTIL.OutputDataReceived += p_WriteData;
LMUTIL.Start();
LMUTIL.BeginOutputReadLine();
}
private void p_WriteData(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Debug.WriteLine(e.Data.ToString());
}
}
I lifted this straight out of a project that does what you need. Subscribe to the p_WriteData event to capture what would appear in the command window.
After all, it is not possible to hide this psexec console window using the Process Class.
It's not necessary to use psexec. I used the WMI stuff instead:
ConnectionOptions remoteConnectionOptions = new ConnectionOptions();
remoteConnectionOptions.Impersonation = ImpersonationLevel.Impersonate;
remoteConnectionOptions.EnablePrivileges = true;
remoteConnectionOptions.Authentication = AuthenticationLevel.Packet;
remoteConnectionOptions.Username = strDomain + #"\" + strUsername;
remoteConnectionOptions.SecurePassword = secPassword;
ManagementScope scope = new ManagementScope(#"\\" + strServername + #"\root\CIMV2", remoteConnectionOptions); ManagementPath p = new ManagementPath("Win32_Process");
ManagementClass classInstance = new ManagementClass(scope, p, null); object[] theProcessToRun = { "myExecutable.exe" };
classInstance.InvokeMethod("Create", theProcessToRun);

Run command line code programmatically using C#

I'm using this code run in windows command prompt..
But I need this done programmatically using C# code
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -pdf "connection
Strings" "C:\Users\XXX\Desktop\connection string\DNN"
try this
ExecuteCommand("Your command here");
call it using process
public void ExecuteCommand(string Command)
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
}
You may use the Process.Start method:
Process.Start(
#"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe",
#"-pdf ""connection Strings"" ""C:\Users\XXX\Desktop\connection string\DNN"""
);
or if you want more control over the shell and be able to capture for example the standard output and error you could use the overload taking a ProcessStartInfo:
var psi = new ProcessStartInfo(#"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe")
{
Arguments = #"-pdf ""connection Strings"" ""C:\Users\XXX\Desktop\connection string\DNN""",
UseShellExecute = false,
CreateNoWindow = true
};
Process.Start(psi);
You should be able to do that using a process
var proc = new Process();
proc.StartInfo.FileName = #"C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe ";
proc.StartInfo.Arguments = string.Format(#"{0} ""{1}""" ""{2}""","-pdf","connection Strings" ,"C:\Users\XXX\Desktop\connection string\DNN");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string outPut = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
var exitCode = proc.ExitCode;
proc.Close();

Categories

Resources