Introduction
This tip shows how to find the default browser command line in registry using Visual C++.
Background
Normally, you use ShellExecute()
or ShellExecuteEx()
to open a URL in the default browser.
But sometimes, you need to know the exact path to the executable. For example, when you want to launch Internet Explorer at low integrity level from a high integrity level process.
Using the Code
Copy the following code into your project:
bool GetDefaultBrowserLaunchPath(LPTSTR *pszFilepath)
{
bool bRes = false;
*pszFilepath = 0;
HKEY hKey = 0;
TCHAR szData[1024] = {0};
DWORD dwDataSize = 0;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_CURRENT_USER, TEXT(
"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice"),
0, KEY_QUERY_VALUE, &hKey))
{
dwDataSize = ARRAYSIZE(szData)*sizeof(szData[0]);
if (ERROR_SUCCESS != RegQueryValueEx
(hKey, TEXT("Progid"), 0, 0, (LPBYTE)&szData, &dwDataSize))
goto Cleanup;
if (!dwDataSize)
goto Cleanup;
RegCloseKey(hKey); hKey = 0;
_tcscat_s(szData, ARRAYSIZE(szData), TEXT("\\shell\\open\\command"));
if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_CLASSES_ROOT, szData,
0, KEY_QUERY_VALUE, &hKey)) goto Cleanup;
}
else
{
if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_CURRENT_USER, TEXT(
"Software\\Classes\\http\\shell\\open\\command"),
0, KEY_QUERY_VALUE, &hKey)) goto Cleanup;
}
if (ERROR_SUCCESS != RegQueryValueEx(hKey, 0, 0, 0, 0, &dwDataSize))
goto Cleanup;
DWORD nMaxSize = dwDataSize/sizeof(TCHAR) + 3 + 1; *pszFilepath = new TCHAR[nMaxSize];
if (ERROR_SUCCESS != RegQueryValueEx(hKey, 0, 0, 0, (LPBYTE)(*pszFilepath), &dwDataSize))
{
delete [] (*pszFilepath);
*pszFilepath = 0;
goto Cleanup;
}
if (!_tcsstr(*pszFilepath, TEXT("%1")))
_tcscat_s(*pszFilepath, nMaxSize, TEXT(" %1"));
bRes = true;
Cleanup:
if (hKey)
RegCloseKey(hKey);
return bRes;
}
Here is how to use the code above:
LPTSTR pszBrowserPath;
if (GetDefaultBrowserLaunchPath(&pszBrowserPath))
{
MessageBox(0, pszBrowserPath, 0, MB_OK);
delete [] pszBrowserPath;
}
If the function succeeds, it returns a command line including a %1
placeholder. You should replace this placeholder with a URL you want to show in the browser.
Points of Interest
The code uses different registry locations to find the default browser command line for WinXP and Vista+.
I would be happy to know if there is a more straightforward way to do the task this tip describes because there is surprisingly too little information on the Internet on how to achieve this.
Launching a low integrity level process from a high integrity level process is out of scope of this article, but there is a very good post on this topic.