アプリケーションをインストールするときにプログラムメニューやデスクトップ上にショートカットを生成したいことがある。そのような場合はCOMインターフェースのIShellLinkを通じて作成する。ショートカットファイルの拡張子には「.lnk」を指定する。
また、この方法でURLへのショートカット作成もできるが一般的ではない。作成したい場合はIUniformResourceLocatorを利用するべきだ。
#include <shlobj.h>
//
// ショートカットの作成
//
// pszLinkにショートカットを保存します。拡張子に「.lnk」を指定してください。
// ショートカットのターゲットはpszFile、説明はpszDescription...とオプションを設定できます。
//
bool CreateShortcut(LPCTSTR pszLink,LPCTSTR pszFile,LPCTSTR pszDescription=NULL,LPCTSTR pszArgs=NULL,LPCTSTR pszWorkingDir=NULL,LPCTSTR pszIconPath=NULL,int nIcon=0,int nShowCmd=SW_SHOWNORMAL)
{
HRESULT hr;
IShellLink* pIShellLink;
IPersistFile* pIPersistFile;
//IShellLinkの作成
pIShellLink = NULL;
hr = ::CoCreateInstance(CLSID_ShellLink,NULL,CLSCTX_INPROC_SERVER,IID_IShellLink,(void**)&pIShellLink);
if(pIShellLink == NULL || FAILED(hr))
return false;
//IPersistFileの取得
pIPersistFile = NULL;
hr = pIShellLink->QueryInterface(IID_IPersistFile,(void**)&pIPersistFile);
if(pIPersistFile == NULL || FAILED(hr))
{
pIShellLink->Release();
return false;
}
//ショートカット詳細設定
hr = pIShellLink->SetPath(pszFile);
if(SUCCEEDED(hr) && pszDescription)
hr = pIShellLink->SetDescription(pszDescription);
if(SUCCEEDED(hr) && pszArgs)
hr = pIShellLink->SetArguments(pszArgs);
if(SUCCEEDED(hr) && pszWorkingDir)
hr = pIShellLink->SetWorkingDirectory(pszWorkingDir);
if(SUCCEEDED(hr) && pszIconPath)
hr = pIShellLink->SetIconLocation(pszIconPath,nIcon);
if(SUCCEEDED(hr))
hr = pIShellLink->SetShowCmd(nShowCmd);
#ifndef UNICODE
WCHAR* pwszUnicode;
int nLen;
//Unicode変換
nLen = ::MultiByteToWideChar(CP_ACP,0,pszLink,-1,NULL,0);
pwszUnicode = new WCHAR[nLen + 1];
if(pwszUnicode == NULL)
{
pIPersistFile->Release();
pIShellLink->Release();
return false;
}
nLen = ::MultiByteToWideChar(CP_ACP,0,pszLink,-1,pwszUnicode,nLen + 1);
if(nLen == 0)
hr = E_FAIL;
//ショートカットの保存
if(SUCCEEDED(hr))
hr = pIPersistFile->Save(pwszUnicode,TRUE);
delete pwszUnicode;
#else
//ショートカットの保存
if(SUCCEEDED(hr))
hr = pIPersistFile->Save(pszLink,TRUE);
#endif
pIPersistFile->Release();
pIShellLink->Release();
return SUCCEEDED(hr) ? true : false;
}
void Test(void)
{
bool ret;
//COM初期化
::CoInitialize(NULL);
ret = CreateShortcut(_T("c:\\test.lnk"),_T("c:\\windows\\notepad.exe"),_T("メモ帳"));
if(ret)
::MessageBox(NULL,_T("ショートカットの作成に成功しました"),_T(""),MB_OK);
else
::MessageBox(NULL,_T("ショートカットの作成に失敗しました"),_T(""),MB_OK);
//COM開放
::CoUninitialize();
}
