在C#中获取进程ID时出现异常

3
我想获取进程ID,尝试使用以下代码:

我想获取进程ID,尝试使用以下代码:

Process myProcess = new Process();
myProcess.StartInfo.FileName = "http://somesite.com";
myProcess.Start();
logs.logging("Afetr Open" + myProcess.Id, 8);

但是我在myProcess.Id这一行遇到了异常:

此对象没有关联的进程。


你确定在调用 myProcess.Id 的时候,你的进程还没有结束吗? - Darin Dimitrov
可能是Find process id when Process.Start returns null?的重复问题。 - Andrew Grinder
3
您正在使用ShellExecute打开一个链接,该链接不会返回进程ID。我确信这是有意的。这篇文章更好地解释了此问题。(https://dev59.com/mWox5IYBdhLWcg3wl1P4)如果您想要进程ID,则需要指定要使用哪个浏览器。 - Equalsk
2个回答

3
如果您将myProcess.StartInfo.FileName = "http://somesite.com";更改为myProcess.StartInfo.FileName = "cmd";,代码就可以运行。 我认为第一段代码并没有创建进程,它只是调用系统打开链接。
您可以手动调用浏览器。例如:
Process myProcess = Process.Start("iexplore", "http://somesite.com");        
var id = myProcess.Id;

可以,谢谢 :) 但是现在我有另一个问题 - 我能在其他标签页中运行两个IE进程而不是其他浏览器吗? - krolik1991
这里有一些解决方案:https://dev59.com/6nA65IYBdhLWcg3wogKe - BWA

1
你可以尝试先获取浏览器的路径,然后将URL作为参数传递来启动它。
    var path = GetStandardBrowserPath();
    var process = Process.Start(path , "http://www.google.com");
    int processId = process.Id ;

它将找到默认浏览器路径,无论是什么。
 private static string GetStandardBrowserPath()
        {
            string browserPath = string.Empty;
            RegistryKey browserKey = null;

            try
            {
                //Read default browser path from Win XP registry key
                browserKey = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);

                //If browser path wasn't found, try Win Vista (and newer) registry key
                if (browserKey == null)
                {
                    browserKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
                }

                //If browser path was found, clean it
                if (browserKey != null)
                {
                    //Remove quotation marks
                    browserPath = (browserKey.GetValue(null) as string).ToLower().Replace("\"", "");

                    //Cut off optional parameters
                    if (!browserPath.EndsWith("exe"))
                    {
                        browserPath = browserPath.Substring(0, browserPath.LastIndexOf(".exe") + 4);
                    }

                    //Close registry key
                    browserKey.Close();
                }
            }
            catch
            {
                //Return empty string, if no path was found
                return string.Empty;
            }
            //Return default browsers path
            return browserPath;
        }

查看源代码,请见Source

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接