下面的代码演示了如何创建一个URL文件,其中参数的含义如下:
pszURL:网络地址,例如http://www.vchelp.net你也可以让它指向一个文件如:file://local_file_name。 pszURLFileName:URL文件名,例如c:/vchelp.url当Windows显示时只会显示vchelp,而不会显示扩展名。 szDescription:对该URL的描述。 szIconFile:显示该URL的图标文件,可以是EXE或DLL。 index:图标在文件中的位置。 HRESULT CreateInterShortcut (LPCSTR pszURL, LPCSTR pszURLfilename, LPCSTR szDescription,LPCTSTR szIconFile = NULL,int nIndex = -1) {//通过ShellLink接口来创建URL HRESULT hres; CoInitialize(NULL); IUniformResourceLocator *pHook; hres = CoCreateInstance (CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER, IID_IUniformResourceLocator, (void **)&pHook); //获得CLSID_InternetShortcut接口 if (SUCCEEDED (hres)) { IPersistFile *ppf; IShellLink *psl; // Query IShellLink for the IPersistFile interface for hres = pHook->QueryInterface (IID_IPersistFile, (void **)&ppf); hres = pHook->QueryInterface (IID_IShellLink, (void **)&psl); if (SUCCEEDED (hres)) { WORD wsz [MAX_PATH]; // buffer for Unicode string // Set the path to the shortcut target. pHook->SetURL(pszURL,0); hres = psl->SetIconLocation(szIconFile,nIndex); if (SUCCEEDED (hres)) { // Set the description of the shortcut. hres = psl->SetDescription (szDescription); if (SUCCEEDED (hres)) { // Ensure that the string consists of ANSI characters. MultiByteToWideChar (CP_ACP, 0, pszURLfilename, -1, wsz, MAX_PATH); // Save the shortcut via the IPersistFile::Save member function. hres = ppf->Save (wsz, TRUE); } } // Release the pointer to IPersistFile. ppf->Release (); psl->Release (); } // Release the pointer to IShellLink. pHook->Release (); } return hres; }
同样如果利用ShellLink接口也能够读取文件,通过GetArguments,GetDescription,GetIconLocation,GetPath等函数可以得到文件的信息。
如果你打开URL文件查看,你会发现文件结构与INI文件类似,例如Visual C++ Help.url文件内容,
[InternetShortcut] URL=http://www.vchelp.net/
因此,我用下边的方法建立一个URL文件也是成功的,而且避免使用了接口
BOOL CreateMyUrlFile(const char * strURL,
const char * strURLFileName,
const char * strIconfile,
const int nIndex)
{
ofstream urlfile;
urlfile.open(strURLFileName, ios::out | ios::trunc );
if(urlfile.is_open())
{
urlfile <<endl<<"[InternetShortcut]"<<endl;
if(strIconfile)
{
urlfile<<"IconIndex="<<nIndex<<endl
<<"IconFile="<<strIconfile<<endl;
}
urlfile<<"URL="<<strURL<<endl;
urlfile.close();
return TRUE;
}
return FALSE;
}
而且,可以通过调用GetPrivateProfileString/WritePrivateProfileString来读/写URL文件。