如何在Windows窗体的后台运行命令**cd..**
? (即用户无法看到它)
谢谢。
请参阅System.Diagnostics.Process http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx
此外,还有这个SO回答了完全相同的问题: https://dev59.com/pHM_5IYBdhLWcg3wPAZF#1469790
示例:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();
您可以初始化一个新的System.Diagnostics.ProcessStartInfo
对象,其中包含启动进程所需的信息,还包括WindowStyle
属性,该属性指示在启动进程时使用的窗口状态,可以是Hidden
、Maximized
、Minimized
或Normal
。在您的情况下,我们将其设置为Hidden
,这样启动的进程将无法接收任何输入或显示来自/发送给用户的输出。
示例
System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); //Initializes a new ProcessStartInfo of name myProcessInfo
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + @"\System32\cmd.exe"; //Sets the FileName property of myProcessInfo to %SystemRoot%\System32\cmd.exe where %SystemRoot% is a system variable which is expanded using Environment.ExpandEnvironmentVariables
myProcessInfo.Arguments = "cd.."; //Sets the arguments to cd..
myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Sets the WindowStyle of myProcessInfo which indicates the window state to use when the process is started to Hidden
System.Diagnostics.Process.Start(myProcessInfo); //Starts the process based on myProcessInfo
截图
以下截图显示了任务管理器,其中显示了由我们的应用程序启动的一个进程。然而,它的窗口是不可见的。
注意:即使关闭应用程序,所启动的进程也不会终止。
另外,要以管理员身份运行一个进程,您可以将进程启动信息的Verb
属性设置为runas
例子
System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); //Initializes a new ProcessStartInfo of name myProcessInfo
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + @"\System32\cmd.exe"; //Sets the FileName property of myProcessInfo to %SystemRoot%\System32\cmd.exe where %SystemRoot% is a system variable which is expanded using Environment.ExpandEnvironmentVariables
myProcessInfo.Arguments = "cd.."; //Sets the arguments to cd..
myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Sets the WindowStyle of myProcessInfo which indicates the window state to use when the process is started to Hidden
myProcessInfo.Verb = "runas"; //The process should start with elevated permissions
System.Diagnostics.Process.Start(myProcessInfo); //Starts the process based on myProcessInfo
注意:如果您启用了用户账户控制,可能会要求您首先允许具有提升权限的过程启动,如果试图调用此过程的应用程序未使用提升的权限运行。
如果您想跳过提示,我认为您应该允许主应用程序以提升的权限启动。要做到这一点,您需要打开您应用程序的清单并确保添加以下行:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
这将简单地告诉您的应用程序仅以提升的权限启动。因此,当您将过程作为管理员调用时,不会出现提示,因为进程调用器正在以管理员身份执行。
感谢,
希望您会发现这有所帮助 :)
/C
。 - newbieguy