I'm trying to let the user choose the browser my application uses to launch urls. Currently it uses the default browser, but some people want to specify a different browser.
I'd like to show only installed browsers in the list, and I'm launching them like this:
Pro开发者_Python百科cess.Start("chrome", url);
(more info)
The problem is, if Chrome isn't installed (and in the path), it'll fail.
How can I check whether this call will fail, without calling it (so I can pre-filter my list, and remove chrome if it's not going to work)?
In Windows all of the installed applications have a key in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
registry key. One solution would be to iterate over all the entries in this key and see if they match the names of your supported browsers.
Once you've got the registry keys for each browser, you can then get the Path
value of each key, and see if the executable file exists in the specified path.
One thing to note is that on 64-bit versions of Windows, 32-bit apps are listed in the HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\App Paths
.
You could wrap Process.Start("chrome", url);
it in a try/catch
(catching the exception thrown when browser is not installed)
Kindness,
Dan
I ended up using this function in C# to detect if chrome is installed without launching browser window and without peeking into windows registry:
bool checkChromeInstalled()
{
try
{
string process = "chrome.exe";
string args = "--no-startup-window --start-in-incognito";
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = process;
psi.Arguments = args;
var chrome_ps = Process.Start(psi);
if (chrome_ps != null)
{
//chrome exists and started successully. exit chrome.
chrome_ps.Kill();
}
//if reached this far, means chrome exist.
return true;
}
catch
{
//got an error, probably chrome is not installed(not sure however).
return false;
}
}
The command line argument --no-startup-window starts chrome in background. Got the chrome switch from this link.
You can call above function like this:
if (!checkChromeInstalled())
{
MessageBox.Show("Please install Google Chrome to run this app.\n\nIf chrome is already installed, make sure 'chrome.exe' is set in Path envirinment variable.");
Application.Exit();
return;
}
精彩评论