Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Console Window while using Process.StartInfo with diffent Username

Tags:

c#

.net

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

like image 368
DaFunkyAlex Avatar asked Apr 27 '26 03:04

DaFunkyAlex


2 Answers

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);
like image 118
Ivan Avatar answered Apr 28 '26 17:04

Ivan


            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.

like image 26
Lee Harrison Avatar answered Apr 28 '26 19:04

Lee Harrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!