2012-05-08 14 views

risposta

57
Process.Start("http://www.google.com"); 
19

Process.Start ([your url]) è davvero la risposta, in tutti i casi, ma estremamente di nicchia. Per completezza, tuttavia, menzionerò che ci siamo imbattuti in un caso di nicchia qualche tempo fa: se stai provando ad aprire un "file: \" url (nel nostro caso, per mostrare la copia locale installata del nostro webhelp), nel lanciare dalla shell, i parametri per l'url sono stati buttati fuori.

La nostra soluzione piuttosto hackish, che io non consiglio a meno che non si verifica un problema con la soluzione "corretta", sembrava qualcosa di simile:

Nel gestore clic per il pulsante:

string browserPath = GetBrowserPath(); 
if (browserPath == string.Empty) 
    browserPath = "iexplore"; 
Process process = new Process(); 
process.StartInfo = new ProcessStartInfo(browserPath); 
process.StartInfo.Arguments = "\"" + [whatever url you're trying to open] + "\""; 
process.Start(); 

la funzione brutto che non si dovrebbe usare meno che Process.Start ([tuo url]) non fa quello che ci si aspetta che sta andando a:

private static string GetBrowserPath() 
{ 
    string browser = string.Empty; 
    RegistryKey key = null; 

    try 
    { 
     // try location of default browser path in XP 
     key = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false); 

     // try location of default browser path in Vista 
     if (key == null) 
     { 
      key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ; 
     } 

     if (key != null) 
     { 
      //trim off quotes 
      browser = key.GetValue(null).ToString().ToLower().Replace("\"", ""); 
      if (!browser.EndsWith("exe")) 
      { 
       //get rid of everything after the ".exe" 
       browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4); 
      } 

      key.Close(); 
     } 
    } 
    catch 
    { 
     return string.Empty; 
    } 

    return browser; 
} 
+0

grazie per le informazioni aggiuntive –

+1

Questo è codifica estremamente piacevole – BoundForGlory

+1

Questa risposta potrebbe utilizzare un aggiornamento per includere Win8 e Win10. (Se qualcuno finisce per implementarlo, modifica questa risposta per includerlo!) – ANeves

Problemi correlati