ShellExecute与Process.Start
在这个答案中 ,作者@Abel建议每当Process.Start
不起作用时使用ShellExecute
。
我什么时候才能使用ShellExecute
– 我从未Process.Start
不起作用的情况?
此外,使用ShellExecute
不是Process.Start
有什么优势吗?
使用ShellExecute而不是Process.Start有什么好处
首先,您需要了解ShellExecute
function。 来自ProcessStartInfo.UseShellExecute
:
使用操作系统shell启动进程时,可以启动任何文档(与具有默认打开操作的可执行文件关联的任何已注册文件类型),并使用Process对象对文件执行操作(如打印) 。 当UseShellExecute为false时,您只能使用Process对象启动可执行文件。
这意味着它将允许您打开具有已分配文件类型的任何文件,例如给定的Word文档。 否则,您只能调用可执行文件。 如果在ProcessStartInfo
将此标志设置为true,则在内部, Process.Start
将调用相同的WinAPI调用 :
public bool Start() { Close(); ProcessStartInfo startInfo = StartInfo; if (startInfo.FileName.Length == 0) throw new InvalidOperationException(SR.GetString(SR.FileNameMissing)); if (startInfo.UseShellExecute) { return StartWithShellExecuteEx(startInfo); } else { return StartWithCreateProcess(startInfo); } }
当您调用ShellExecute
,您正在使用PInvoke直接调用WinAPI。 使用Process.Start,您只需调用托管包装器,这通常更方便使用。