How can I start a process in the background? - c#

I can't seem to find an answer on Google or here on StackOverflow.
How can I start a process in background (behind the active window)? Like, when the process starts, it will not interrupt the current application the user is using.
The process won't pop out in front of the current application, it will just start.
This is what I'm using:
Process.Start(Chrome.exe);
Chrome pops up in front of my application when it's started. How can I make it start in background?
I've also tried:
psi = new ProcessStartInfo ("Chrome.exe");
psi.UseShellExecute = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(psi);
But there's no difference at all from the previous one.
Thanks.

Try this:
Process p = new Process();
p.StartInfo = new ProcessStartInfo("Chrome.exe");
p.StartInfo.WorkingDirectory = #"C:\Program Files\Chrome";
p.StartInfo.CreateNoWindow = true;
p.Start();
Also, if that doesn't work, try adding
p.StartInfo.UseShellExecute = false;

Below code should do what you need:
class Program
{
static void Main(string[] args)
{
var handle = Process.GetCurrentProcess().MainWindowHandle;
Process.Start("Chrome.exe").WaitForInputIdle();
SetForegroundWindow(handle.ToInt32());
Console.ReadLine();
}
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
}

Related

How to start a process in the background and read standard output

I am new to C#, I have to start a very time consuming process from my C# program of course without bearing the loss of ui freeze, also I want to read the output printed by the program in cmd and at last I want a stop button so that I can close the program whenever I want...
Please help..
try:
using System.Diagnostics;
void startProcess()
{
Process p = new Process();
p.StartInfo.FileName = "FileName";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
var output = p.StandardOutput.ReadToEnd();
}
MethodInvoker starter = new MethodInvoker(startProcess);
starter.BeginInvoke(null, null);
for ending the process:
p.close()
Use something like this:
void StartProcess(){
Process p = new Process();
p.StartInfo.FileName = "yourfile.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
var readingThread = new System.Threading.Thread(() => {
while (!p.StandardOutput.EndOfStream){
Console.WriteLine(p.StandartOutput.ReadLine());
System.Threading.Thread.Sleep(1);
}
}
readingThread.Start();
}

.NET System.Process: when you redirect StandardError, console window receives no output

I want to get the error output of a console program in case it crashes. But I want the standard output to display in the console window. However, if I redirect the standard error, nothing is output to the console window.
Dim p As New Process
p.StartInfo.Filename = filename
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardError = True
p.EnableRaisingEvents = True
p.Start
p.BeginReadErrorLine
So now if the launched process (a console program) crashes, I get the error output as expected. However, the standard output is not visible in the console program.
I wrote a test program to launch.
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(i);
}
object m = null;
string s = m.ToString();
}
I expect to see the numbers 0 - 999 scroll in the console window and get the error output through the redirect, but I see nothing in the console window unless nothing is redirected.
I haven't found any questions dealing with this issue. Is this a defect or something i've overlooked?
I tried reproducing same, But I couldn't. Here's my code where I am redirecting only error but still I am able to see output on my console window:
public class Program
{
static void Main(string[] args)
{
ExecuteCommand(#"cmd.exe", #"/c C:\Users\*****\Documents\Test\ConsoleApp1.exe");
}
public static int ExecuteCommand(string exePath, string cmdText)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = exePath;
startInfo.Arguments = cmdText;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
process.BeginErrorReadLine();
process.WaitForExit();
return process.ExitCode;
}
}
Here's my output:
Am I doing something different form what You have tried?

C# Process Start Stuck

I wrote a simple TCP Server application,
when the program gets the request it will call an exe file to do something.
The application works fine on my PC.
But when I run on another PC the thread will stuck because it stuck in process start, so I checked the task manager whether the exe file did run. and it really work.
I have no idea how to solve it.
Here is my code:
System.Diagnostics.Process process = new System.Diagnostics.Process();
string path = System.Environment.CurrentDirectory;
process.StartInfo.WorkingDirectory = path;
process.StartInfo.FileName = "FileTransferTool\\FileTransfer.exe";
process.StartInfo.Arguments = argument;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.CreateNoWindow = false;
process.Start(); // the thread stuck here
I print out the message, it shows
System.ComponentModel.Win32Exception (0x80004005):
The system cannot find the file specified at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startIn
fo)
at System.Diagnostics.Process.Start() at ClassPackage.DsUploadFiletoNC.Start(Object[] param)
I have solved this problem by adding another process to call cmd.exe on the top of the main program, the code shown as below :
And the program will run as Administrator, but I don't know why
static void Main(string[] args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
string path = System.Environment.CurrentDirectory;
process.StartInfo.WorkingDirectory = #"C:\Windows\System32";
process.StartInfo.FileName = "cmd.exe";
//process.StartInfo.FileName = "FileTransferTool\\circle.txt";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardInput = true;
//process.StartInfo.CreateNoWindow = false;
process.Start();
using (TCPServer server = new TCPServer())
{
server.Start();
Console.WriteLine("Socket Server Start...");
Console.ReadKey(true);
}
}

How to run Defrag.exe for optimize the harddisk in windows application c#

I have developed one windows application in which i have some implemented feature now i want to implement optimize hard disk so i got to know about defrag.exe .so i wrote some code but its not working for me. can anyone what am doing wrong ?
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
p.StartInfo.Verb = "runas";
p.StartInfo.FileName =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Defrag.exe");
p.StartInfo.Arguments = #"c:\ /A";
try
{
p.Start();
p.WaitForExit();
string a= p.StandardOutput.ToString();
See my comment on your previous post. That aside, you need to set a few extra parameters - working sample below. You may also need to elevate privileges in order for your scenario to work. If this is the case, then see this post.
static void Main(string[] args)
{
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
p.StartInfo.Verb = "runas";
p.StartInfo.FileName =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Defrag.exe");
p.StartInfo.Arguments = #"c:\ /A";
// Additional properties set
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
// Fixed your request for standard with ReadToEnd
string result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
Adding another option - try the below. To use runas, you need to set StartInfo.UseShellExecute = true which means you cant redirect the standard output - would this still work for you? Another option is to run your whole program as admin How do I force my .NET application to run as administrator? - this will allow you to redirect your output and run with elevated permissions.
static void Main(string[] args)
{
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
p.StartInfo.Verb = "runas";
p.StartInfo.FileName =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "Defrag.exe");
p.StartInfo.Arguments = #"c:\ /A";
// Additional properties set
//p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = true;
//p.StartInfo.CreateNoWindow = true;
p.Start();
// Fixed your request for standard with ReadToEnd
//string result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}

create process and attach C#

I have a doubt, when I create a new process iexplore, and this process opens one single page, I would like know if the page loads correctly. How can I learn if the page load fails ?. Is there any way to catch an error from iexplore process?
I have this demo code, but doesn't work correctly
string navegador = "C:\\program files (x86)\\Internet Explorer\\iexplore.exe";
Process p = new Process();
p.StartInfo.FileName = navegador;
ProcessStartInfo processStartInfo = new ProcessStartInfo(navegador);
p.EnableRaisingEvents = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo = processStartInfo;
p.StartInfo.Arguments = "google.com";
p.Start();
Process currentProcess = Process.GetCurrentProcess();
Process[] localByName = Process.GetProcessesByName("iexplore");
Process[] localAll = Process.GetProcesses();
p.OutputDataReceived += new DataReceivedEventHandler(
prsProjectTypes_OutputDataReceived);
p.BeginOutputReadLine();
errorMessage = p.StandardError.ReadToEnd();
p.WaitForExit();
Thank you for any help.
Assuming you are working WPF, you should look at the Web Browser control rather than launching a separate process. This will give you access to the LoadCompleted event which seems to be what you're looking for.

Categories