如何使用c#隐藏命令窗口

时间:2015-09-02 07:05:21

标签: c# .net command-prompt psexec

构建将执行exe文件的控制台应用程序(pagesnap.exe)。我想在执行期间隐藏它的窗口(pagesnap.exe)。怎么做。

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是本地PC。稍后会尝试使用远程PC。

我尝试过的事情

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";

更新:我已将使用输出类型的pagesnap构建为Windows应用程序而不是控制台。现在,cmd窗口没有出现。似乎这是我唯一的方式

1 个答案:

答案 0 :(得分:2)

只需调用以下功能即可。将参数作为命令和工作目录传递

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();

        }
    }