Process.Start 启动进程但返回 null [英] Process.Start launches the process but returns null

查看:86
本文介绍了Process.Start 启动进程但返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows 窗体应用程序,它只做 1 件事:启动 Edge,终止进程:

I have a windows form application which does 1 thing: launch Edge, the kill the process:

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        Process edgeProc = new Process();
        edgeProc = Process.Start("microsoft-edge:.exe");
        edgeProc.Kill();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
    }
}

我没有装有 Win10 + Edge 的机器来调试此代码,但我可以间接访问 Windows 10 虚拟机.我构建我的应用程序并在该虚拟机上运行 exe,Edge 启动但随后抛出异常:

I don't have a machine with Win10 + Edge to debug this code on, but I indirectly have access to a Windows 10 VM. I build my application and run the exe on that VM, Edge launches but then an exception is thrown:

未将对象引用设置为对象的实例.

Object reference not set to an instance of an object.

在 EdgeLauncher.Form1.Form1_Load(Object sender, EventArgs e)

at EdgeLauncher.Form1.Form1_Load(Object sender, EventArgs e)

我了解什么是 NullReferenceException 并且非常熟悉 这个问题.

I understand what a NullReferenceException is and am plenty familiar with this question.

MSDN 说:

与进程资源关联的新进程,如果没有启动进程资源,则为 null.

A new Process that is associated with the process resource, or null if no process resource is started.

Edge 正在启动,因此 edgeProcess 不应为 null.那么为什么我会收到此错误?

Edge is being launched, so edgeProcess shouldn't be null. So why am I getting this error?

推荐答案

您正在使用 shell 来执行该命令.不能保证与此相关的过程.仅仅因为出现一个新窗口并不意味着一个新进程已经启动:)

You're using the shell to execute that command. There is no guarantee a process associated with that. Just because a new window appears doesn't mean a new process has been started :)

如果您总是想启动一个新进程,请不要使用 UseShellExecute - 不用说,这有其自身的复杂性.

If you always want to start a new process, don't use UseShellExecute - needless to say, this has complications of its own.

这篇关于Process.Start 启动进程但返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆