C# を使用して既定の Web ブラウザーの名前を確認する方法はありますか? (Firefox、Google Chrome など)
例を教えてください。
Internet Explorer が既定のブラウザーとして設定されている場合、他の回答は機能しません。私の Windows 7 PC では、HKEY_CLASSES_ROOT\http\shell\open\command
IE 用に更新されていません。この背後にある理由は、既定のプログラムの処理方法が Windows Vista から導入された変更である可能性があります。
Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice
デフォルトで選択されたブラウザは、レジストリ キーで値で見つけることができます Progid
。( 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;
}
}
ブラウザの実行可能ファイルへのパスも必要な場合は、次のようにアクセスして、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.
}
}
ここで例を見ることができますが、主に次のように実行できます。
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;
}
これは古くなっていますが、他の人が使用できるように、私自身の調査結果を追加します。の値はHKEY_CURRENT_USER\Software\Clients\StartMenuInternet
、このユーザーのデフォルトのブラウザー名を提供する必要があります。
インストールされているすべてのブラウザを列挙したい場合は、
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet
で見つかった名前を使用しHKEY_CURRENT_USER
てデフォルトのブラウザを識別し、HKEY_LOCAL_MACHINE
その方法でパスを見つけることができます。
ここでの応答を正しいプロトコル処理と組み合わせて作成したものを次に示します。
/// <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;
}