Using C code, how to invoke the default browser to open "about:blank" (a blank page)?
I've tried many methods, here are some that don't work:
<Windows.h>
's ShellExecuteW
or ShellExecute
passing "open"
as its 2nd argumenthttp:about:blank
insteadResults:
What's more, using something like http:about:blank
or http://about:blank
may be not correct.
Maybe the only valid url pointing to a blank is about:blank
I've found that AssocQueryString
helps (requiring to link against shlwapi.dll
),
This is AssocQueryStringW
's reference
Here is one possible version of C++
code:
#include<shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "Shell32.lib")
#define F_ASSOC ASSOCF_NONE
#define assoc(buffer, sizep) ::AssocQueryStringW(F_ASSOC, ASSOCSTR_EXECUTABLE,\
L"http", L"open", (buffer), (sizep))
DWORD getDefaultBrowser(LPWSTR &pszPath){
DWORD size = 0;
assoc(NULL, &size); // get required buffer size, returns S_FALSE
pszPath = new WCHAR[size];
HRESULT hr = assoc(pszPath,&size); // assert(hr==S_OK);
return size;
// remember `delete[]pszPath;`
}
int main(){
LPWSTR browserPath;
DWORD len = getDefaultBrowser(browserPath);
if (len == 0)return -1;
ShellExecuteW(NULL, L"open", browserPath, L"about:blank", NULL, SW_SHOW);
delete[] browserPath;
}
Also, corresponding C
code:
#include<stdlib.h>
#include<Windows.h>
#include<shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "Shell32.lib")
#define F_ASSOC ASSOCF_NONE
#define assoc(buffer, sizep) AssocQueryStringW(F_ASSOC, ASSOCSTR_EXECUTABLE, \
L"http", L"open", (buffer), (sizep));
DWORD getDefaultBrowser(LPWSTR* pOut){
DWORD size = 0;
assoc(NULL, &size); // get required buffer size, returns S_FALSE
*pOut = (LPWSTR)malloc(size * sizeof(WCHAR));
HRESULT hr = assoc(*pOut,&size); // assert(hr==S_OK);
return size;
// remember `free(pOut);`
}
int main(){
//Get default web browser path
LPWSTR browserPath;
DWORD len = getDefaultBrowser(&browserPath);
if(len == 0) return -1;
ShellExecuteW(NULL, L"open", browserPath, L"about:blank", NULL, SW_SHOW);
free(browserPath);
}