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

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

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

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

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

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

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

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

例如

  System.Diagnostics.ProcessStartInfo procStartInfo = new System.DiagnosticsProcessStartInfo("xcopy", "  "); procStartInfo.WindowStyle = ProcessWindowStyle.Hidden; 

你可以尝试添加

 process.StartInfo.UseShellExecute = false; 

到你的过程

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

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

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

 ShowWindow(hWnd, 0); 

0隐藏窗口,1显示窗口

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

pinvoke.net enumwindows(user32)