How to run this app with hidden or even minimized console? - c#

var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #"C:\Program Files\CPUID\CPU-Z\cpuz.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
for(; ; )
{
process.Start();
Thread.Sleep(20000);
process.Kill();
}
This program need to be hidden or even minimized?
Can someone explain to me how to upgrade this?

Add these lines to your code
this.ShowInTaskbar = false;
this.FormBorderStyle = FormBorderStyle.FixedToolWindow;

Related

Run windows command without cmd.exe from C#

I am attempting to run a windows command (e.g. whoami) without calling cmd.exe (or powershell) directly using C#.
Within VB this is possible using CreateObject(WScript.Shell) it obviously does not have to be the same method as within the VB, although that would be nice, but I just do not want to call cmd.exe directly.
How would I be able to achieve this?
This runs a console program, waits for exit and reads the output. I changed the cmd to ping since that takes longer and I can verify no console window opens.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "ping.exe";
startInfo.Arguments = "google.com";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
// This wasn't needed
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
textBox1.Text = processTemp.StandardOutput.ReadToEnd();
processTemp.WaitForExit();
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
You could call whoami.exe and capture the output directly.
The key is UseShellExecute = false to run the executable directly.
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #$"{Environment.ExpandEnvironmentVariables("%systemroot%")}\system32\whoami.exe",
Arguments = // Put any command line arguments here
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
string line = proc.StandardOutput.ReadToEnd();

child process window not appearing

I am trying to create a child process from a c# console app that shows the console. I tried the following but no window appeared.
ProcessStartInfo = new ProcessStartInfo(name)
{
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
WindowStyle = ProcessWindowStyle.Maximized,
CreateNoWindow = false,
ErrorDialog = false
};
if (args != null)
{
ProcessStartInfo.Arguments = args;
}
if (workingDirectory != null)
{
ProcessStartInfo.WorkingDirectory = workingDirectory;
}
Process = new Process {EnableRaisingEvents = true, StartInfo = ProcessStartInfo};
Process.Start();
The right way to run child process in the parent’s console is to setup UseShellExecute property of ProcessStartInfo class. Let’s consider an example that executes time command. Why time? Because it reads from standard input. This way you will know which console it uses.
public class Program
{
public static void Main(string[] args)
{
var processInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c time"
};
Console.WriteLine("Starting child process...");
using (var process = Process.Start(processInfo))
{
process.WaitForExit();
}
}
}
We left the default value of UseShellExecute, which is true. It means that a shell will be used for the child process. Using shell means that a new console will be created.
Let’s flip the value of UseShellExecute to false.
public class Program
{
public static void Main(string[] args)
{
var processInfo = new ProcessStartInfo
{
UseShellExecute = false, // change value to false
FileName = "cmd.exe",
Arguments = "/c time"
};
Console.WriteLine("Starting child process...");
using (var process = Process.Start(processInfo))
{
process.WaitForExit();
}
}
}

How to restart a C# console app in the same Cmd window? [duplicate]

Can I start a process (using C# Process.Start()) in the same console as the calling program? This way no new window will be created and standard input/output/error will be the same as the calling console application. I tried setting process.StartInfo.CreateNoWindow = true; but the process still starts in a new window (and immediately closes after it finishes).
You shouldn't need to do anything other than set UseShellExecute = false, as the default behaviour for the Win32 CreateProcess function is for a console application to inherit its parent's console, unless you specify the CREATE_NEW_CONSOLE flag.
I tried the following program:
private static void Main()
{
Console.WriteLine( "Hello" );
var p = new Process();
p.StartInfo = new ProcessStartInfo( #"c:\windows\system32\netstat.exe", "-n" )
{
UseShellExecute = false
};
p.Start();
p.WaitForExit();
Console.WriteLine( "World" );
Console.ReadLine();
}
and it gave me this output:
You could try redirecting the output of this process and then printing it on the calling process console:
public class Program
{
static void Main()
{
var psi = new ProcessStartInfo
{
FileName = #"c:\windows\system32\netstat.exe",
Arguments = "-n",
RedirectStandardOutput = true,
UseShellExecute = false
};
var process = Process.Start(psi);
while (!process.HasExited)
{
Thread.Sleep(100);
}
Console.WriteLine(process.StandardOutput.ReadToEnd());
}
}
Alternative approach using the Exited event and a wait handle:
static void Main()
{
using (Process p = new Process())
{
p.StartInfo = new ProcessStartInfo
{
FileName = #"netstat.exe",
Arguments = "-n",
RedirectStandardOutput = true,
UseShellExecute = false
};
p.EnableRaisingEvents = true;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
p.Exited += (s, e) => mre.Set();
p.Start();
mre.WaitOne();
}
Console.WriteLine(p.StandardOutput.ReadToEnd());
}
}

Run CheckDisk with RedirectStandardOutput

Running ChkDsk without redirecting StandardOutput works without an error like this:
var processStartInfo = new ProcessStartInfo(#"chkdsk.exe", "D:");
processStartInfo.UseShellExecute = false;
var process = Process.Start(processStartInfo);
process.WaitForExit();
if (process.ExitCode != 0)
throw new Exception("did not work");
When redirecting StandardOutput, the process ends with ExitCode 3.
var processStartInfo = new ProcessStartInfo(#"chkdsk.exe", "D:");
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
var process = Process.Start(processStartInfo);
process.WaitForExit();
if (process.ExitCode != 0)
throw new Exception("did not work");
Doing the same thing with e.g. net use and redirected StandardOutput works without an error
var processStartInfo = new ProcessStartInfo(#"net ", "use");
Why? How can chkdsk be executed and StandardOutput be redirected?
Environment: Win 7 Pro x64, UAC disabled, Logged on as Administrator, Dot Net 4.0, VS 2012, WPF Application
I just ran this code with no problem and with an exit code of 0.
var cd = RunProcessDirect("chkdsk.exe", "c:", false);
protected ConsoleData RunProcessDirect(string processPath, string args,
bool isHidden)
{
Process process = SetupProcess(processPath, args, isHidden);
process.Start();
ConsoleData data = new ConsoleData();
data.StandardOutput = process.StandardOutput.ReadToEnd();
data.StandardError = process.StandardError.ReadToEnd();
data.ExitCode = process.ExitCode;
return data;
}
private Process SetupProcess(string processPath, string args,
bool isHidden)
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = isHidden
? ProcessWindowStyle.Hidden
: ProcessWindowStyle.Normal;
startInfo.CreateNoWindow = isHidden;
startInfo.FileName = processPath;
startInfo.Arguments = args;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
return process;
}
public class ConsoleData
{
public string StandardOutput { get; set; }
public string StandardError { get; set; }
public int ExitCode { get; set; }
}
cd.StandardOutput contained all the text output from the program, cd.StandardError was empty, and cd.ExitCode is 0.
Don't worry about the IsHidden stuff, that is just extra flair on my method that I didn't feel like taking off.
You must be running Visual Studio as Administrator and it will execute or you can add a application manifest file(add->new item->general->application manifest file) and changing this line <requestedExecutionLevel level="asInvoker" uiAccess="false" /> to this <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> which will just promp you to restart visual studio as administrator.
Simple answer, start a console process on non console application; if you would like to redirect standard output, please do a redirect standard input as well (even you are not using it).
So, just add below two lines in your code, it will work.
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardError = true;
This code works, runs chkdsk via cmd, and writes into log whole chkdsk output.
public int StartCheckDisc()
{
var process = new Process
{
StartInfo =
{
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Normal,
FileName = "cmd",
Arguments = "/C chkdsk C:",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true
}
};
process.Start();
var output = process.StandardOutput.ReadToEnd();
var exitCode = process.ExitCode;
var errorCode = process.StandardError.ReadToEnd();
Log.Instance.Info(output);
Log.Instance.Info(exitCode);
Log.Instance.Info(errorCode);
process.WaitForExit();
return exitCode;
}

Windows Form Application with Console Application

I have a console application that asks for a SourcePath when started.. when I enter the Source Path, It asks for DestinationPath... when i enter DestinationPath it starts some execution
My Problem is to Supply these path via a windows application, means i need to create a window form application that will supply these parameters to the console application automatiocally after certain time interval
can it be achieved or not... if yes, plese help... its very Urgent...
ohh..
I have tried a lot of code that i can not paste hear all but some that i use to start the application are...
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = #"C:\Program Files\Wondershare\PPT2Flash SDK\ppt2flash.exe";
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
psi.CreateNoWindow = false;
psi.Arguments = input + ";" + output;
Process p = Process.Start(psi);
and
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = #"C:\Program Files\Wondershare\PPT2Flash SDK\ppt2flash.exe",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
if (process.Start())
{
Redirect(process.StandardError, text);
Redirect(process.StandardOutput, text);
MessageBox.Show(text);
}
private void Redirect(StreamReader input, string output)
{
new Thread(a =>{var buffer = new char[1];
while (input.Read(buffer, 0, 1) > 0)
{
output += new string(buffer);
};
}).Start();
}
but nothing seems to be working
You can add parameters to your ProcessStartInfo like this:
ProcessStartInfo psi = new ProcessStartInfo(#"C:\MyConsoleApp.exe",
#"C:\MyLocationAsFirstParamter C:\MyOtherLocationAsSecondParameter");
Process p = Process.Start(psi);
this will startup the console app with 2 parameters.
Now in your console app you have the
static void Main(string[] args)
the string array args is what contains the parameters, now all you have to do is get them when your app starts.
if (args == null || args.Length < 2)
{
//the arguments are not passed correctly, or not at all
}
else
{
try
{
yourFirstVariable = args[0];
yourSecondVariable = args[1];
}
catch(Exception e)
{
Console.WriteLine("Something went wrong with setting the variables.")
Console.WriteLine(e.Message);
}
}
This may or may not be the exact code that you need, but at least will give you an insight in how to accomplish what you want.

Categories

Resources