简体   繁体   中英

How to launch the user's default browser with search criteria?

I found this link: C# Launch default browser with a default search query

But with FireFox as my default browser, it tries to find a file named as whatever is in the quotes in the selected Answer there.

Code;

    //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;
    }

I found the GetDefaultBrowser() code somewhere on StackOverflow yesterday but I can't find the link now. The weird thing is though, I have Chrome set as my default browser but that registry key still says FireFox.

Is there a more simple way to launch the default browser and use their default search provider to look up a term?

Try this:

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

Edit: Now using correct Google link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM