2012-11-29 8 views

Antwort

19

Sie können here suchen Sie nach einem Beispiel, vor allem aber kann es wie folgt geschehen:

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

Wenn ich den Internet Explorer als Standardbrowser festgelegt, es nicht zu funktionieren scheint für mich. :/Dieser bestimmte Registrierungsspeicherort wird nicht aktualisiert, um auf IE zu zeigen. –

+2

Diese Methode scheint nicht mehr zu funktionieren. – tofutim

+0

@tofutim Könnten Sie das ein bisschen mehr ausarbeiten? –

37

Die derzeit akzeptierte Antwort nicht für mich arbeiten, wenn Internet Explorer als Standardbrowser eingestellt ist. Auf meinem Windows 7 PC ist die HKEY_CLASSES_ROOT\http\shell\open\command nicht für IE aktualisiert. Der Grund dafür könnten Änderungen sein, die ab Windows Vista bei der Behandlung von Standardprogrammen eingeführt werden.

Sie können den standardmäßig ausgewählten Browser im Registrierungsschlüssel Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice mit dem Wert Progid finden. (thanks goes to Broken Pixels)

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

Im Fall müssen Sie auch den Pfad der ausführbaren Datei des Browsers Sie darauf zugreifen können wie folgt, die Progid mit aus ClassesRoot abzurufen.

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. 
    } 
} 
+1

Persönlich denke ich, dass es viel eleganter ist, den% 1-Parameter in der abgerufenen Zeichenfolge einzugeben, ihn in Programm und Parameter aufzuteilen und ihn so auszuführen, wie er in der Registrierung definiert ist, anstatt den ausführbaren Pfad abzurufen. – Nyerguds

+0

@Darren Danke, dass Sie Opera, Safari und Edge mit eingeschlossen haben! Was zum Teufel ist mit Edges Name in der Registrierung? Sind Sie sicher, dass dies auf allen Systemen derselbe ist (es scheint eine zufällige Zeichenfolge zu sein)? –

+1

@StevenJeuris Ich kann mir nicht sicher sein, welchen Wert Edge hat und habe diesen fast nicht hinzugefügt. Ich fand das [Antwort] (http://stackoverflow.com/a/32724723/1229237) mit dem gleichen Wert, also hat es sich in fast zwei Jahren nicht geändert. Hoffentlich ist das sicher, aber ich bin ein wenig skeptisch wie du. Opera sieht gut aus, Safari war seit etwa 2012 nicht mehr in Entwicklung, hatte aber immer noch eine Kopie und dachte, es wäre gut, sie einzuschließen. –

5

Ich habe gerade eine Funktion dafür:

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

Dies wird die Jahre gekommen, aber ich werde einfach meine eigenen Ergebnisse, die anderen Personen zu verwenden. Der Wert HKEY_CURRENT_USER\Software\Clients\StartMenuInternet sollte Ihnen den Standardbrowsernamen für diesen Benutzer geben.

Wenn Sie alle installierten Browser auflisten möchten, verwenden Sie HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet

Sie den Namen in HKEY_CURRENT_USER verwenden Sie können den Standard-Browser in HKEY_LOCAL_MACHINE und dann der Weg, den Weg finden, zu identifizieren.

+0

Nein. Nicht in Win10. Es sagt Firefox, während mein Standard Chrome ist. – Nyerguds

+0

Diese Methode ist nicht schlecht. Die Liste der Browser unter 'HKEY_LOCAL_MACHINE \ SOFTWARE \ Clients \ StartMenuInternet' ist für die zeigen, was installiert ist, während es einige hilfreiche Informationen wie' ... StartMenuInternet \ got 'S \ Capabilities FileAssociations' \ und Strings installieren, wo verwendet werden, um den Standardbrowser zu ändern. – u8it

+0

Der tatsächliche "Standard-Browser" wird jedoch am funktionellsten durch den Progid unter HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ Shell \ Associations \ UrlAssociations \ http \ UserChoice bestimmt. Aus meinen Tests bestimmen die Browser selbst, ob sie "Standardwerte" sind oder nicht. Firefox versteht sich als Standard mit nur http, Chrome überprüft https auch, und IE will alle seine möglichen Ausfall gefüllt – u8it

1

Hier ist etwas, das ich die Antworten aus der Kombination von hier mit dem richtigen Protokollverarbeitung eckt:

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

Das war wirklich nützlich für meine Lösung, obwohl ich auf dem Windows 10-Computer eines Clients den Process.Start für eine ProcessStartInfo wechseln musste, um das Arbeitsverzeichnis festlegen zu können. Es ist jedoch nicht Yandex als Standard-Browser aufgenommen, etwas, das ich noch untersuchen muss. – VorTechS

+0

Ehrlich gesagt, habe _Visual Studio_ zwei verschiedene Browser geöffnet, wenn ich zweimal auf denselben Link klicke. Die ganze Sache ist eine riesige Sauerei. Wichtiger Hinweis auf das Arbeitsverzeichnis. Ich werde das bearbeiten. – Nyerguds

0

WINDOWS 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; 
    } 
Verwandte Themen