アプリケーションをインストールするときにお気に入りにURLを追加したいことがある。そのような場合はCOMインターフェースのIUniformResourceLocatorを通じて作成する。ショートカットファイルの拡張子には「.url」を指定する。
#include <shlobj.h>
#include <intshcut.h>
//
// URLショートカットの作成
//
// pszLinkにショートカットを保存します。拡張子に「.url」を指定してください。
//
bool CreateInternetShortcut(LPCTSTR pszFile,LPCTSTR pszURL)
{
HRESULT hr;
IPersistFile* pIPersistFile;
IUniformResourceLocator* pIUniformResourceLocator;
pIUniformResourceLocator = NULL;
hr = ::CoCreateInstance(CLSID_InternetShortcut,NULL,CLSCTX_INPROC_SERVER,IID_IUniformResourceLocator,(void**)&pIUniformResourceLocator);
if(pIUniformResourceLocator == NULL || FAILED(hr))
return false;
hr = pIUniformResourceLocator->QueryInterface(IID_IPersistFile,(void**)&pIPersistFile);
if(pIPersistFile == NULL || FAILED(hr))
{
pIUniformResourceLocator->Release();
return false;
}
hr = pIUniformResourceLocator->SetURL(pszURL,0);
#ifdef _UNICODE
if(SUCCEEDED(hr))
hr = pIPersistFile->Save(pszFile,TRUE);
#else
WCHAR* pwszUnicode;
int nLen;
//Unicode変換
nLen = ::MultiByteToWideChar(CP_ACP,0,pszFile,-1,NULL,0);
pwszUnicode = new WCHAR[nLen + 1];
if(pwszUnicode == NULL)
{
pIPersistFile->Release();
pIUniformResourceLocator->Release();
return false;
}
nLen = ::MultiByteToWideChar(CP_ACP,0,pszFile,-1,pwszUnicode,nLen + 1);
if(nLen == 0)
hr = E_FAIL;
//ショートカットの保存
if(SUCCEEDED(hr))
hr = pIPersistFile->Save(pwszUnicode,TRUE);
delete pwszUnicode;
#endif
pIPersistFile->Release();
pIUniformResourceLocator->Release();
return SUCCEEDED(hr) ? true : false;
}
void Test(void)
{
bool ret;
//COM初期化
::CoInitialize(NULL);
ret = CreateInternetShortcut(_T("c:\\test.url"),_T("http://www.google.co.jp/"));
if(ret)
::MessageBox(NULL,_T("ショートカットの作成に成功しました"),_T(""),MB_OK);
else
::MessageBox(NULL,_T("ショートカットの作成に失敗しました"),_T(""),MB_OK);
//COM開放
::CoUninitialize();
}
