在C#应用程序中隐藏命令窗口

时间:2010-08-09 12:47:10

标签: c# .net command-prompt xcopy

在你说一个重复的问题之前,请让我解释一下(因为我读过所有类似的主题)。

我的应用程序具有以下两种设置:

  procStartInfo.CreateNoWindow = true;
  procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

并且还将WindowsApplication作为输出类型。

当我调用命令行命令时,黑色窗口STILL出现。我还能做些什么来隐藏窗户吗?并非所有命令都会发生,XCOPY是黑色窗口闪烁的情况。这种情况只会发生在我正在XCOPYing的目的地已经包含该文件时,它会提示我是否要替换它。即使我传入/ Y它仍会短暂闪现。

我愿意使用vbscript,如果这会有所帮助,但还有其他想法吗?

客户端将调用我的可执行文件,然后传入命令行命令,即:

C:\MyProgram.exe start XCOPY c:\Test.txt c:\ProgramFiles\

以下是该应用程序的完整代码:

class Program
{
    static void Main(string[] args)
    {      
            string command = GetCommandLineArugments(args);

            // /c tells cmd that we want it to execute the command that follows and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c " + command);

            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;

            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo = procStartInfo;
            process.Start();

        }

    private static string GetCommandLineArugments(string[] args)
    {
        string retVal = string.Empty;

        foreach (string arg in args)
            retVal += " " + arg;


        return retVal;
    }
}

4 个答案:

答案 0 :(得分:9)

问题是您正在使用cmd.exe。只会隐藏控制台窗口,而不是您要求它启动的进程的控制台窗口。使用cmd.exe没有什么意义,除非您尝试执行它自己实现的一些命令。像COPY一样。

如果需要cmd.exe,仍然可以禁止显示窗口,您必须使用/ B选项启动。输入start /?在命令提示符下查看选项。不是它有帮助,你不能使用START COPY。

xcopy.exe中存在一个特定的怪癖,可能会让你失望。如果您不重定向输入,它执行。它无法在没有诊断的情况下运行。

答案 1 :(得分:4)

我看到您正在调用 cmd ,然后将该命令作为参数传递。而是直接调用命令

e.g。

    System.Diagnostics.ProcessStartInfo procStartInfo = new System.DiagnosticsProcessStartInfo("xcopy", "<sourcedir> <destdir> <other parameters>");

procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

答案 2 :(得分:4)

您可以尝试添加

process.StartInfo.UseShellExecute = false; 

到您的流程

答案 3 :(得分:0)

我有类似的任务 - 可以通过API调用在创建后隐藏窗口。 (在你的情况下,你可能需要一个辅助线程。)

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

如果你知道新窗口的句柄,你可以打电话

ShowWindow(hWnd, 0);

0隐藏窗口,1显示窗口

要获取Window的句柄,请查看:

pinvoke.net enumwindows(user32)

相关问题