C# 控制台窗口赢得';隐藏
我需要停止然后重新启动Windows Update服务,但我希望控制台在显示或根本不显示后关闭。我尝试了它在这里说的一切,但控制台窗口仍然不会自行消失C# 控制台窗口赢得';隐藏,c#,C#,我需要停止然后重新启动Windows Update服务,但我希望控制台在显示或根本不显示后关闭。我尝试了它在这里说的一切,但控制台窗口仍然不会自行消失 Process process = new Process(); process.StartInfo.FileName = "cmd"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExec
Process process = new Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.Arguments = "/C start \"wuauserv\"";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.Start();
process.WaitForExit();
我建议不要你的 启动服务 以下方法尝试启动由服务名称指定的服务。然后等待服务运行或超时 发生
public static void StartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
停止服务
以下方法尝试停止指定的服务,并等待该服务停止或出现超时
public static void StartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
public static void StopService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
catch
{
// ...
}
}
然后,您可以在不显示任何控制台窗口的情况下控制服务,同时将
重定向标准输出设置为重定向标准错误
设置为真
process.startInfo.RedirectStandardOutput = true;
process.startInfo.RedirectStandardError = true;
还要确保UseShellExecute
必须设置为false
,否则设置CreateNoWindow=true
就没有意义了,你不仅仅是想启动/停止服务,而不是自己运行服务进程吗?使用cmd shell这样做是愚蠢的。关于如何直接从C#停止和启动Windows服务,我没有看到任何反对票?两者都看不出原因。@BugFinder,downvote的一个原因是唯一的链接答案。这是一个短页面-从中复制和粘贴数据似乎太多了。。但我想这可能是一个错误answer@BugFinder,我是为你做的。谢谢。成功了。不知道为什么从过程的角度尝试了一切,但都没有成功。