如何使用搜索条件启动用户的默认浏览器?

时间:2013-11-01 13:03:44

标签: c# winforms default-browser

我找到了这个链接: C# Launch default browser with a default search query

但是使用FireFox作为我的默认浏览器,它会尝试在所选的答案中找到一个名为“引号”中的文件。

代码;

    //ToolStripMenu Click event to launch default browser and search internet for the value in a particular cell
    private void tsmSearch_Click(object sender, EventArgs e)
    {
        int key = mp.GetRowAt(gdcErrorLogDefaultView, rowX, rowY);

        if (key < 0)
            return;

        string ex = gdcErrorLogDefaultView.GetRowCellValue(key, "Exception").ToString();

        string name = GetDefaultBrowser();

        Process.Start(name, "\"?" + ex + "\"");
    }

    //Gets default browser from registry
    private string GetDefaultBrowser()
    {
        string name;
        RegistryKey regKey = null;

        try
        {
            //set the registry key we want to open
            regKey = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false);

            //get rid of the enclosing quotes
            name = regKey.GetValue(null).ToString().ToLower().Replace("" + (char)34, "");

            //check to see if the value ends with .exe (this way we can remove any command line arguments)
            if (!name.EndsWith("exe"))
                //get rid of all command line arguments (anything after the .exe must go)
                name = name.Substring(0, name.LastIndexOf(".exe") + 4);

        }
        catch (Exception ex)
        {
            name = string.Format("ERROR: An exception of type: {0} occurred in method: {1} in the following module: {2}", ex.GetType(), ex.TargetSite, this.GetType());
        }
        finally
        {
            //check and see if the key is still open, if so
            //then close it
            if (regKey != null)
                regKey.Close();
        }

        return name;
    }

我昨天在StackOverflow上找到了GetDefaultBrowser()代码,但我现在找不到链接。但奇怪的是,我将Chrome设置为我的默认浏览器,但该注册表项仍然显示FireFox。

是否有更简单的方法来启动默认浏览器并使用其默认搜索提供商来查找字词?

1 个答案:

答案 0 :(得分:1)

试试这个:

string searchQuery = "this is a search";
Process.Start("https://www.google.com/search?q=" + Uri.EscapeDataString(searchQuery));

修改:现在使用正确的Google链接