我们什么时候需要将UseShellExecute设置为True?

// // Summary: // Gets or sets a value indicating whether to use the operating system shell // to start the process. // // Returns: // true to use the shell when starting the process; otherwise, the process is // created directly from the executable file. The default is true. [DefaultValue(true)] [MonitoringDescription("ProcessUseShellExecute")] [NotifyParentProperty(true)] public bool UseShellExecute { get; set; } 

如果我们产生一个新的进程,我们什么时候需要设置UseShellExecute为True?

UseShellExecute布尔属性与使用Windows ShellExecute函数和CreateProcess函数相关 – 简单的答案是,如果UseShellExecute为true,那么Process类将使用ShellExecute函数,否则将使用CreateProcess

更长的答案是, ShellExecute函数用于打开指定的程序或文件 – 这大致等同于input要在运行对话框中执行的命令并单击确定,这意味着它可以用于(例如):

  • 使用默认浏览器打开.html文件或网页,而无需知道该浏览器是什么,
  • 打开Word文档,而不必知道Word的安装path是什么
  • 运行batch file
  • PATH上运行任何命令

例如:

 Process p = new Process(); p.StartInfo.UseShellExecute = true; p.StartInfo.FileName = "www.google.co.uk"; p.Start(); 

这是非常容易使用,多function和强大的但有一些缺点:

  • 不能redirect标准input/输出/错误句柄
  • 不可能为subprocess指定安全描述符(或其他很酷的东西)
  • 如果您对实际运行的内容进行假设,则有可能引入安全漏洞:

     // If there is an executable called "notepad.exe" somewhere on the path // then this might not do what we expect p.StartInfo.FileName = "notepad.exe"; p.Start(); 

CreateProcess是一种更精确的启动进程的方式 – 它不searchpath,并允许您redirectsubprocess的标准input或输出(等等)。 然而, CreateProcess的缺点是我上面给出的4个例子都没有工作(试一试看)。

总之,如果下面的情况你应该设置UseShellExecute为false:

  • 你想redirect标准的input/输出/错误(这是最常见的原因)
  • 您不想search可执行文件的path(例如出于安全原因)

相反,如果您想打开文档,url或batch file等,则应将UseShellExecute保持UseShellExecute true,而不必明确指定可执行文件的path。

我认为主要是为非可执行文件。 例如,如果试图打开一个.html文件,如果您必须将UseShellExecute设置为true ,那么将在用户默认设置的浏览器中打开.html文件。

来自MSDN :

将此属性设置为false可以使您redirectinput,输出和错误stream。

如果UserName属性不是null或空string,则UseShellExecute必须为false,否则将在调用Process.Start(ProcessStartInfo)方法时引发InvalidOperationException。

使用操作系统shell启动进程时,可以启动任何文档(与具有默认打开操作的可执行文件相关联的任何已注册文件types),并使用Process组件对文件执行操作(例如打印)。 当UseShellExecute为false时,您可以只使用Process组件启动可执行文件。

如果将ErrorDialog属性设置为true,则UseShellExecute必须为true。

如果我们要隐藏当前的应用程序可执行文件窗口,那么UseShellExecute应该设置为true