小编典典

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

c#

//
// 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?


阅读 982

收藏
2020-05-19

共1个答案

小编典典

UseShellExecute布尔属性是关系到使用的Windows
ShellExecute的功能VS的CreateProcess的功能-
简单的答案是,如果UseShellExecute为真,那么Process类将使用该ShellExecute功能,否则它会使用CreateProcess

较长的答案是该ShellExecute函数用于打开指定的程序或文件-
与在运行对话框中键入要执行的命令并单击“确定”大致等效,这意味着该函数可用于(例如):

  • 使用默认浏览器打开.html文件或网络,而无需知道该浏览器是什么,
  • 打开Word文档,而无需知道Word的安装路径是什么
  • 运行批处理文件
  • 在上运行任何命令 PATH

例如:

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

它非常易于使用,用途广泛且功能强大,但存在一些缺点:

  • 无法重定向标准输入/输出/错误句柄
  • 不可能为子进程指定安全描述符(或其他很酷的东西)
  • 如果您对将实际运行的内容进行假设,则有可能引入安全漏洞:
    // 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是启动进程的一种更为精确的方法-
它不搜索路径,并允许您重定向子进程的标准输入或输出(除其他外)。CreateProcess但是,缺点是我上面给出的4个示例都不起作用(尝试一下然后看看)。

总之,UseShellExecute如果满足以下条件,则应将其设置为false:

  • 您想重定向标准输入/输出/错误(这是最常见的原因)
  • 您不想在可执行文件的路径中搜索(例如,出于安全原因)

相反,UseShellExecute如果要打开文档,URL或批处理文件等,则应保持true,而不是必须显式提供可执行文件的路径。

2020-05-19