Подтвердить что ты не робот

Как найти веб-браузер по умолчанию с помощью С#?

Есть ли способ узнать имя моего браузера по умолчанию с помощью С#? (Firefox, Google Chrome и т.д.)

Не могли бы вы показать мне пример?

4b9b3361

Ответ 1

Вы можете посмотреть здесь для примера, но в основном это можно сделать следующим образом:

internal string GetSystemDefaultBrowser()
{
    string name = string.Empty;
    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 the value
    return name;

}

Ответ 2

Текущий принятый ответ не работает для меня, когда Internet Explorer установлен как браузер по умолчанию. На моем ПК с Windows 7 HKEY_CLASSES_ROOT\http\shell\open\command не обновляется для IE. Причиной этого могут быть внесенные изменения, начиная с Windows Vista в том, как обрабатываются программы по умолчанию.

Вы можете найти выбранный по умолчанию браузер в разделе реестра Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice со значением Progid. (спасибо за сломанные пиксели)

const string userChoice = @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice";
string progId;
BrowserApplication browser;
using ( RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey( userChoice ) )
{
    if ( userChoiceKey == null )
    {
        browser = BrowserApplication.Unknown;
        break;
    }
    object progIdValue = userChoiceKey.GetValue( "Progid" );
    if ( progIdValue == null )
    {
        browser = BrowserApplication.Unknown;
        break;
    }
    progId = progIdValue.ToString();
    switch ( progId )
    {
        case "IE.HTTP":
            browser = BrowserApplication.InternetExplorer;
            break;
        case "FirefoxURL":
            browser = BrowserApplication.Firefox;
            break;
        case "ChromeHTML":
            browser = BrowserApplication.Chrome;
            break;
        case "OperaStable":
            browser = BrowserApplication.Opera;
            break;
        case "SafariHTML":
            browser = BrowserApplication.Safari;
            break;
        case "AppXq0fevzme2pys62n3e0fbqa7peapykr8v":
            browser = BrowserApplication.Edge;
            break;
        default:
            browser = BrowserApplication.Unknown;
            break;
    }
}

Если вам также нужен путь к исполняемому файлу браузера, вы можете получить к нему доступ следующим образом, используя Progid, чтобы извлечь его из ClassesRoot.

const string exeSuffix = ".exe";
string path = progId + @"\shell\open\command";
FileInfo browserPath;
using ( RegistryKey pathKey = Registry.ClassesRoot.OpenSubKey( path ) )
{
    if ( pathKey == null )
    {
        return;
    }

    // Trim parameters.
    try
    {
        path = pathKey.GetValue( null ).ToString().ToLower().Replace( "\"", "" );
        if ( !path.EndsWith( exeSuffix ) )
        {
            path = path.Substring( 0, path.LastIndexOf( exeSuffix, StringComparison.Ordinal ) + exeSuffix.Length );
            browserPath = new FileInfo( path );
        }
    }
    catch
    {
        // Assume the registry value is set incorrectly, or some funky browser is used which currently is unknown.
    }
}

Ответ 3

Я только что сделал для этого функцию:

    public void launchBrowser(string url)
    {
        string browserName = "iexplore.exe";
        using (RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"))
        {
            if (userChoiceKey != null)
            {
                object progIdValue = userChoiceKey.GetValue("Progid");
                if (progIdValue != null)
                {
                    if(progIdValue.ToString().ToLower().Contains("chrome"))
                        browserName = "chrome.exe";
                    else if(progIdValue.ToString().ToLower().Contains("firefox"))
                        browserName = "firefox.exe";
                    else if (progIdValue.ToString().ToLower().Contains("safari"))
                        browserName = "safari.exe";
                    else if (progIdValue.ToString().ToLower().Contains("opera"))
                        browserName = "opera.exe";
                }
            }
        }

        Process.Start(new ProcessStartInfo(browserName, url));
    }

Ответ 4

Это стареет, но я просто добавлю свои собственные выводы для других. Значение HKEY_CURRENT_USER\Software\Clients\StartMenuInternet должно дать вам имя браузера по умолчанию для этого пользователя.

Если вы хотите перечислить все установленные браузеры, используйте HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet

Вы можете использовать имя, найденное в HKEY_CURRENT_USER, чтобы определить браузер по умолчанию в HKEY_LOCAL_MACHINE, а затем найти путь таким образом.

Ответ 5

ОКНА 10

internal string GetSystemDefaultBrowser()
    {
        string name = string.Empty;
        RegistryKey regKey = null;

        try
        {
            var regDefault = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.htm\\UserChoice", false);
            var stringDefault = regDefault.GetValue("ProgId");

            regKey = Registry.ClassesRoot.OpenSubKey(stringDefault + "\\shell\\open\\command", false);
            name = regKey.GetValue(null).ToString().ToLower().Replace("" + (char)34, "");

            if (!name.EndsWith("exe"))
                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
        {
            if (regKey != null)
                regKey.Close();
        }

        return name;
    }

Ответ 6

Здесь что-то, что я приготовил из сочетания ответов здесь с правильной обработкой протокола:

/// <summary>
///     Opens a local file or url in the default web browser.
///     Can be used both for opening urls, or html readme docs.
/// </summary>
/// <param name="pathOrUrl">Path of the local file or url</param>
/// <returns>False if the default browser could not be opened.</returns>
public static Boolean OpenInDefaultBrowser(String pathOrUrl)
{
    // Trim any surrounding quotes and spaces.
    pathOrUrl = pathOrUrl.Trim().Trim('"').Trim();
    // Default protocol to "http"
    String protocol = Uri.UriSchemeHttp;
    // Correct the protocol to that in the actual url
    if (Regex.IsMatch(pathOrUrl, "^[a-z]+" + Regex.Escape(Uri.SchemeDelimiter), RegexOptions.IgnoreCase))
    {
        Int32 schemeEnd = pathOrUrl.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal);
        if (schemeEnd > -1)
            protocol = pathOrUrl.Substring(0, schemeEnd).ToLowerInvariant();
    }
    // Surround with quotes
    pathOrUrl = "\"" + pathOrUrl + "\"";
    Object fetchedVal;
    String defBrowser = null;
    // Look up user choice translation of protocol to program id
    using (RegistryKey userDefBrowserKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\" + protocol + @"\UserChoice"))
        if (userDefBrowserKey != null && (fetchedVal = userDefBrowserKey.GetValue("Progid")) != null)
            // Programs are looked up the same way as protocols in the later code, so we just overwrite the protocol variable.
            protocol = fetchedVal as String;
    // Look up protocol (or programId from UserChoice) in the registry, in priority order.
    // Current User registry
    using (RegistryKey defBrowserKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Classes\" + protocol + @"\shell\open\command"))
        if (defBrowserKey != null && (fetchedVal = defBrowserKey.GetValue(null)) != null)
            defBrowser = fetchedVal as String;
    // Local Machine registry
    if (defBrowser == null)
        using (RegistryKey defBrowserKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Classes\" + protocol + @"\shell\open\command"))
            if (defBrowserKey != null && (fetchedVal = defBrowserKey.GetValue(null)) != null)
                defBrowser = fetchedVal as String;
    // Root registry
    if (defBrowser == null)
        using (RegistryKey defBrowserKey = Registry.ClassesRoot.OpenSubKey(protocol + @"\shell\open\command"))
            if (defBrowserKey != null && (fetchedVal = defBrowserKey.GetValue(null)) != null)
                defBrowser = fetchedVal as String;
    // Nothing found. Return.
    if (String.IsNullOrEmpty(defBrowser))
        return false;
    String defBrowserProcess;
    // Parse browser parameters. This code first assembles the full command line, and then splits it into the program and its parameters.
    Boolean hasArg = false;
    if (defBrowser.Contains("%1"))
    {
        // If url in the command line is surrounded by quotes, ignore those; our url already has quotes.
        if (defBrowser.Contains("\"%1\""))
            defBrowser = defBrowser.Replace("\"%1\"", pathOrUrl);
        else
            defBrowser = defBrowser.Replace("%1", pathOrUrl);
        hasArg = true;
    }
    Int32 spIndex;
    if (defBrowser[0] == '"')
        defBrowserProcess = defBrowser.Substring(0, defBrowser.IndexOf('"', 1) + 2).Trim();
    else if ((spIndex = defBrowser.IndexOf(" ", StringComparison.Ordinal)) > -1)
        defBrowserProcess = defBrowser.Substring(0, spIndex).Trim();
    else
        defBrowserProcess = defBrowser;

    String defBrowserArgs = defBrowser.Substring(defBrowserProcess.Length).TrimStart();
    // Not sure if this is possible / allowed, but better support it anyway.
    if (!hasArg)
    {
        if (defBrowserArgs.Length > 0)
            defBrowserArgs += " ";
        defBrowserArgs += pathOrUrl;
    }
    // Run the process.
    defBrowserProcess = defBrowserProcess.Trim('"');
    if (!File.Exists(defBrowserProcess))
        return false;
    ProcessStartInfo psi = new ProcessStartInfo(defBrowserProcess, defBrowserArgs);
    psi.WorkingDirectory = Path.GetDirectoryName(defBrowserProcess);
    Process.Start(psi);
    return true;
}

Ответ 7

Как я прокомментировал в ответе Стивена, у меня был случай, когда этот метод не работал. Я использую 64-разрядную версию Windows 7 Pro SP1. Я скачал и установил браузер Opera и обнаружил, что ключ reg HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice описанный в его ответе, был пустым, то есть не ProgId значения ProgId.

Я использовал Process Monitor, чтобы наблюдать, что происходит, когда я открывал URL-адрес в браузере по умолчанию (нажав "Пуск"> "Выполнить" и набрав " https://www.google.com ") и обнаружил, что после того, как он проверил вышеупомянутый раздел реестра и не смог найти значение ProgId, он нашел то, что ему нужно, в HKEY_CLASSES_ROOT\https\shell\open\command (после того, как также проверил и не смог найти его в нескольких других ключах). Хотя Opera установлена в качестве браузера по Default значение по Default в этом ключе содержит следующее:

"C:\Users\{username}\AppData\Local\Programs\Opera\launcher.exe" -noautoupdate -- "%1"

Я продолжал тестировать это на Windows 10, и он ведет себя по-другому - больше в соответствии с ответом Стивена. Он нашел значение ProgId " ProgId в HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice. Кроме того, HKEY_CLASSES_ROOT\https\shell\open\command ключ HKEY_CLASSES_ROOT\https\shell\open\command на компьютере под управлением Windows 10 не хранит путь командной строки браузера по умолчанию в HKEY_CLASSES_ROOT\https\shell\open\command - найденное мной значение

"C:\Program Files\Internet Explorer\iexplore.exe" %1

Итак, вот моя рекомендация, основанная на том, что я наблюдал в Process Monitor:

Сначала попробуйте процесс Стивена, и если там нет ProgID в HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice, то посмотрите на значения по умолчанию в HKEY_CLASSES_ROOT\https\shell\open\command. Конечно, я не могу гарантировать, что это сработает, главным образом потому, что я видел, как он смотрел в кучу других мест, прежде чем нашел его в этом ключе. Тем не менее, алгоритм, безусловно, может быть улучшен и задокументирован здесь, если и когда я или кто-то еще столкнусь со сценарием, который не соответствует описанной мной модели.